“Square Roots” loop:
JavaScript
x
6
1
while True:
2
y = (x+ a/x) / 2
3
if y == x:
4
return x
5
x = y
6
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:
JavaScript
1
12
12
1
a mysqrt(a) math.sqrt(a) diff
2
- --------- ------------ ----
3
1.0 1.0 1.0 0.0
4
2.0 1.41421356237 1.41421356237 2.22044604925e-16
5
3.0 1.73205080757 1.73205080757 0.0
6
4.0 2.0 2.0 0.0
7
5.0 2.2360679775 2.2360679775 0.0
8
6.0 2.44948974278 2.44948974278 0.0
9
7.0 2.64575131106 2.64575131106 0.0
10
8.0 2.82842712475 2.82842712475 4.4408920985e-16
11
9.0 3.0 3.0 0.0
12
Here’s what I wrote:
JavaScript
1
20
20
1
import math
2
3
def mysqrt(a):
4
x = a/5
5
while True:
6
y = (x+ a/x) / 2
7
if y == x:
8
return x
9
x = y
10
11
def test_square_root():
12
a = 1.0
13
print('a', repr(mysqrt(a)).rjust(6), repr(math.sqrt(a)).rjust(12), 'diff'.rjust(10))
14
print("- --------- ------------ ----")
15
while a < 10.0:
16
print(a, " ", mysqrt(a), " ", math.sqrt(a), " ", abs(mysqrt(a)-math.sqrt(a)))
17
a += 1
18
19
test_square_root()
20
Here’s what I got:
JavaScript
1
12
12
1
a 1.0 1.0 diff
2
- --------- ------------ ----
3
1.0 1.0 1.0 0.0
4
2.0 1.414213562373095 1.4142135623730951 2.220446049250313e-16
5
3.0 1.7320508075688772 1.7320508075688772 0.0
6
4.0 2.0 2.0 0.0
7
5.0 2.23606797749979 2.23606797749979 0.0
8
6.0 2.449489742783178 2.449489742783178 0.0
9
7.0 2.6457513110645907 2.6457513110645907 0.0
10
8.0 2.82842712474619 2.8284271247461903 4.440892098500626e-16
11
9.0 3.0 3.0 0.0
12
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.