Encapsulate the following Python code from Section 7.5 in a function named my_sqrt that takes a as a parameter, chooses a starting value for x, and returns an estimate of the square root of a.
while True:
y = (x + a/x) / 2.0
if y == x:
break
x = y
def my_sqrt(a):
x = a
while True:
y = (x + a/x) / 2.0
if y == x:
break
x = y
return x
a = int(input("Enter a positive number: "))
x = my_sqrt(a)
print("Square root of", a, "is", x)
Comments
Leave a comment