i am in need of help with this homework. The instructions are as followed: Package Newton's method for approximating square roots in a function named newton. This function expects the input number as an argument and returns the estimate of its square root. The script should also include a main function that allows the user to compute the square roots of inputs until the user presses the enter/return key. This is what I have so far:
tolerance = 0.000001
""" Returns the square root of x """
#Performs the successive approximations
estimate = 1.0
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance: # Break out of loop if difference is less than tolerance
return estimate # While the difference value is > TOLERANCE, the process continues
"""Allows the user to obtain square roots."""
#Receive the input number from the user
x = input("Enter a positive number or enter/return to quit: ")
if x == "": #if user presses "Enter" then exit the program
break # Otherwise, continue the process of allowing new numbers
x = float(x)
#Output the result
print("The programs estimate of the square root of ", x, "is ", round(newton(x),2))
print("Python's estimate: ", math.sqrt(x))
I tested it out, but it seems like the calculation is not accurate, can anyone help me?
Thank you everyone for your helpful inputs in solving my problem. The code now works since I moved the return outside of the loop. Now for phase 2 of my homework converting the current function to a recursive function. Any suggestions?