Home > front end >  How to loop over a condition until the values have converged? (Newton Raphson Method)
How to loop over a condition until the values have converged? (Newton Raphson Method)

Time:10-21

For the Newton-Raphson Method, I'm asked to write a loop to call the function until it has converged so that the values of x(n) and x(n 1) differ by less than a small number e=10^-8, however, I am not quite sure how to create this loop.

Here's my code so far

def newton_step(f, fp, x0):
     return x0-(f(x0)/fp(x0))

import numpy as np
def f(x):
    return x**3   x**2  2 

def fp(x): 
    return 3*x**2   2*x

x = newton_step(f, fp, (x0))
count = 0 #to count the number of iterations required to satisfy the condition
while (x0 - x) <= 10**-8:
    x0 = newton_step(f, fp, (x0))
    count  = 1
    print(x0, x)

CodePudding user response:

Looks like your comparison operator is backwards, try:

while (x0 - x) > 10**-8:

so that it will loop, continuing while the diff is greater than 10^-8 (breaking out of the loop once it is less than that value)

Also, you'll want to make sure that your code sets an initial value for x0 before the loop (so there is something to compare)

CodePudding user response:

I can see at least 2 issues with your code -

  1. You don't update x
  2. if x0<x then the loop will end but they can differ in more the 10^-8
  3. Wrong conditionn

To sum this up I would change the loop -

while abs(x0-x) >= 10**-8:
    new_x = newton_step(f, fp, (x0))
    x = x0
    x0 = new_x
    count  =1
    print(x0, x)

CodePudding user response:

Your while loop runs as long as the difference is smaller, but it should run as long as the difference is bigger. Change while (x0 - x) <= 10**-8 to while (x0 - x) >= 10**-8.

  • Related