Question #115576

Part 1


Encapsulate the following Python code from Section 7.5 in a function named m_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 in the following using a while loop, where "diff" is the absolute value of the difference between my_sprt(a) and math.sqrt(a).

Expert's answer

import math


def my_sqrt(a):
    x = 1
    while True:
        y = (x + a / x) / 2.0
        if y == x:
            break
        x = y

    return y


def test_sqrt():
    for a in range(1000, 1020):
        approxsqrt = my_sqrt(a)
        actualsqrt = math.sqrt(a)
        print("a =", a,
              "approx. sqrt =", approxsqrt,
              "actual sqrt =", actualsqrt,
              "difference =", abs(approxsqrt - actualsqrt))

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!

LATEST TUTORIALS
APPROVED BY CLIENTS