We are learning Python programming language, and we are trying to figure out an example that approximates the square root of input argument a.
The following source code initializes x, and repeats the iteration until the error $|x^2 - a| < \epsilon$. The variable eps ($\epsilon$) is the upper bound of allowed error.
def approximate_square_root(a):
print("Approximating to the square root of {} ...".format(a))
eps = 1.0e-6
itr = 0
if a > 0.0:
x = a
while abs(x*x - a) > eps:
print("\titr: {}, a: {}, x: {}".format(itr, a, x))
itr += 1
x = (x + a/x) / 2
print("The square root of {} is {}".format(a, x))
print("Finished in {} iternations".format(itr))
else:
print("No square root for negative value {}".format(a))
return
We have verified the above function, e.g., by calling approximate_square_root(4.0), it gets the following output:
Approximating to the square root of 4.0 ...
itr: 0, a: 4.0, x: 4.0
itr: 1, a: 4.0, x: 2.5
itr: 2, a: 4.0, x: 2.05
itr: 3, a: 4.0, x: 2.000609756097561
The square root of 4.0 is 2.0000000929222947
Finished in 4 iternations
Our Question:
We are new in this area, and need help to understand the mathematical reasons behind this algorithm, especially, the iterative $x = \frac{x + \frac{a}{x}}{2}$.
We highly appreciate your help.