“Square Roots” loop:
while True: y = (x+ a/x) / 2 if y == x: return x x = y
Copy the loop from “Square Roots” and encapsulate it in a function called mysqrt that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a. To test it, write a function named test_square_root that prints a table like this:
a mysqrt(a) math.sqrt(a) diff - --------- ------------ ---- 1.0 1.0 1.0 0.0 2.0 1.41421356237 1.41421356237 2.22044604925e-16 3.0 1.73205080757 1.73205080757 0.0 4.0 2.0 2.0 0.0 5.0 2.2360679775 2.2360679775 0.0 6.0 2.44948974278 2.44948974278 0.0 7.0 2.64575131106 2.64575131106 0.0 8.0 2.82842712475 2.82842712475 4.4408920985e-16 9.0 3.0 3.0 0.0
Here’s what I wrote:
import math def mysqrt(a): x = a/5 while True: y = (x+ a/x) / 2 if y == x: return x x = y def test_square_root(): a = 1.0 print('a', repr(mysqrt(a)).rjust(6), repr(math.sqrt(a)).rjust(12), 'diff'.rjust(10)) print("- --------- ------------ ----") while a < 10.0: print(a, " ", mysqrt(a), " ", math.sqrt(a), " ", abs(mysqrt(a)-math.sqrt(a))) a += 1 test_square_root()
Here’s what I got:
a 1.0 1.0 diff - --------- ------------ ---- 1.0 1.0 1.0 0.0 2.0 1.414213562373095 1.4142135623730951 2.220446049250313e-16 3.0 1.7320508075688772 1.7320508075688772 0.0 4.0 2.0 2.0 0.0 5.0 2.23606797749979 2.23606797749979 0.0 6.0 2.449489742783178 2.449489742783178 0.0 7.0 2.6457513110645907 2.6457513110645907 0.0 8.0 2.82842712474619 2.8284271247461903 4.440892098500626e-16 9.0 3.0 3.0 0.0
As you can see, the array is not neatly aligned. How can I print an array if the elements do not have the same length? Thank you!
Advertisement
Answer
Adjust the print statement to print each element to a fixed number of decimal places using {0:.8f} {0:.10f} and {0:.4f} respectively, or your desired coloumn width.