Home > database >  Newton's method of succesive approximations
Newton's method of succesive approximations

Time:07-19

I was trying to build a program to based on the inputs use Newton's method of successive approximations and calculate the answer, using while and if statements, but after running the program, it only collects the input from the user and do not follow up with anything. I would really appreciate some help.

x = float(input("Number you want to know, the square root of: "))
y = float(input("What is your guess ? "))
z = float
a = float

while (True):
    if (abs(y - x) < 0.001):
        print (y)
        break
    else:
        z = (x / y)
        a = ((z   y)/2)
        y = a

CodePudding user response:

you can try :

while(True):
    if (abs(y*y - x) < 0.001)

CodePudding user response:

Consider the case where you want to know the square root of 2. So x will be 2 and y will approach the correct answer. x never changes here, so when will abs(√2 - 2) even be less than 0.001? Then answer is never, which is why your code never exists the loop.

You should be comparing the previous estimate to the new estimate and stopping when the updated value is lower than you tolerance. For example:

x = 2
y = 1

while (True):
        print (y)
        a = ((x / y   y)/2)
        if abs(y - a) < .000001: # has the estimate changed enough?
            break
        y = a

Will quickly converge, printing:

1
1.5
1.4166666666666665
1.4142156862745097
1.4142135623746899
  • Related