In: Computer Science
Write a module that contains a function sqrt(y, tol=1e-6), which computes a square root of a number using Heron’s algorithm with guaranteed relative error less then tol. The module should run as a program that asks for user input and prints output when executed using run sqrt.py. Heron’s algorithms for finding x such that y = x^2 works as follows. First, you come up with an initial guess for x; think what it should be. Then, you update x using the following formula: xnew = 1/2 (xold + y/xold) . Computation ends once the relative deviation between x^2 and y is less then the required value.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#code
#required method
def sqrt(y, tol=1e-6):
#starting with x=y/2
x=y/2
#looping until difference between x*x and y
is less than tol
while
abs((x*x)-y)>tol:
#finding new value
for x, applying heron's equation
x=0.5*(x+(y/x))
#returning the value for x
return x
#main program
if __name__ == '__main__':
#reading a number
n=float(input('Enter a number:
'))
#printing the number and its square
root
print('Square root of {} is
{}'.format(n,sqrt(n)))
#output
Enter a number: 2
Square root of 2.0 is 1.4142135623746899