def sq(n, threshold=1e-6, max_iter=1000):
= 1
x = 1 + threshold # make sure the tolerance starts bigger than the threshold
tol = 0
iterations
while tol > threshold and iterations < max_iter:
= 0.5 * (x + n / x)
xnew = np.abs(xnew - x)
tol = xnew
x = iterations + 1
iterations
if iterations >= max_iter:
print("Failed to converge")
return None
else:
return x
Comments on HW2 - iteration
Fundamentals of Data Science
def sq(n, tol=1e-6, max_iter=1000):
= 1
x = 1
tol = 0
iterations
while tol > threshold:
= 0.5 * (x + n / x)
xnew = np.abs(xnew - x)
tol = xnew
x = iterations + 1
iterations if iterations > max_iter:
print("Failed to converge")
return None
return x