Answer to Question #277744 in Python for solokin

Question #277744

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).


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.


1
Expert's answer
2021-12-09T08:50:19-0500
import math
def my_sqrt(a):
    x0 = a
    x1 = 1
    while (x0 != x1):
        x0 = x1
        x1 = (x0 + a/x0) / 2
    return x0

def test_sqrt(max_a):
    for a in range(1, max_a+1):
        my_val = my_sqrt(a)
        math_val = math.sqrt(a)
        diff = abs(my_val - math_val)
        print(f'a = {a} | my_sqrt(a) = {my_val} | math.sqrt(a) = {math_val} '
            + f'| diff = {diff}')

def main():
    test_sqrt(25)

if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS