61.0k views
0 votes
Package Newton’s method for approximating square roots (Case Study: 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 square roots of inputs until she presses the enter/return key

User Sam Perry
by
3.2k points

1 Answer

3 votes

Answer:

def newton(n):

#Define the variables.

t = 0.000001

esti = 1.0

#Calculate the square root

#using newton method.

while True:

esti = (esti + n / esti) / 2

dif = abs(n - esti ** 2)

if dif <= t:

break

#Return the result.

return esti

#Define the main function.

def main():

#Continue until user press enters.

while True:

try:

#Prompt the user for input.

n = int(input("Enter a number (Press Enter to stop):"))

#display the results.

print("newton = %0.15f" % newton(n))

except:

return

#Call the main function.

main()

User Moby Disk
by
3.6k points