Part 1
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
Part 2
Write a function named test_sqrt that prints a table like the following using a while loop, where "diff" is the absolute value of the difference between my_sqrt(a) and math.sqrt(a).
import math
def my_sqrt(a):
if a == 0:
return 0
x = 1
while True:
y = (x + a/x) / 2.0
if y == x:
break
x = y
return y
def test_sqrt():
k = 0
while k < 20:
my = my_sqrt(k)
std = math.sqrt(k)
diff = abs(my - std)
s = 'a = {0} | my_sqrt(a) = {1} | math.sqrt(a) = {2} | diff = {3}'.format(k, my, std, diff)
print(s)
k += 1
test_sqrt()
Comments
Leave a comment