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).
a = 1 | my_sqrt(a) = 1 | math.sqrt(a) = 1.0 | diff = 0.0
a = 2 | my_sqrt(a) = 1.41421356237 | math.sqrt(a) = 1.41421356237 | diff = 2.22044604925e-16
a = 3 | my_sqrt(a) = 1.73205080757 | math.sqrt(a) = 1.73205080757 | diff = 0.0
a = 4 | my_sqrt(a) = 2.0 | math.sqrt(a) = 2.0 | diff = 0.0
a = 5 | my_sqrt(a) = 2.2360679775 | math.sqrt(a) = 2.2360679775 | diff = 0.0
a = 6 | my_sqrt(a) = 2.44948974278 | math.sqrt(a) = 2.44948974278 | diff = 0.0
a = 7 | my_sqrt(a) = 2.64575131106 | math.sqrt(a) = 2.64575131106 | diff = 0.0
a = 8 | my_sqrt(a) = 2.82842712475 | math.sqrt(a) = 2.82842712475 | diff = 4.4408920985e-16
a = 9 | my_sqrt(a) = 3.0 | math.sqrt(a) = 3.0 | diff = 0.0
Modify your program so that it outputs lines for a values from 1 to 25 instead of just 1 to 9.
import math
def mysqrt(number):
temp = number/2
while True:
temp_root = (temp + number/temp) / 2
if temp_root == temp:
return temp_root
break
temp = temp_root
def test_sqrt(list_a):
l1a = "a"
l1b = "mysqrt(a)"
l1c = "math.sqrt(a)"
l1d = "diff"
l2a = "-"
l2b = "---------"
l2c = "------------"
l2d = "----"
spac1 = " "
spac2 = " " * 3
spac3 = ""
print(l1a, spac1, l1b, spac2, l1c, spac3, l1d)
print(l2a, spac1, l2b, spac2, l2c, spac3, l2d)
for row in list_a:
l1 = float(row)
l2 = mysqrt(row)
l3 = math.sqrt(row)
l4 = abs(mysqrt(row) - math.sqrt(row))
print(l1, "{:<13f}".format(l2), "{:<13f}".format(l3), l4)
test_sqrt(range(1,26))
Comments
Leave a comment