Search code examples
pythonlocal-variablesnewtons-method

Newton's Method to convergence but I get Unbound Error


I have a assignment where I have to find out if some values for x_0 converge, but my code seems to pop up a Unbound Local error when i test values over 0.5.

import numpy as np

from sympy import *

import sympy
from math import atan
from scipy import misc

x = symbols('x')

def f(x):
    return atan(x)+1

def newton(x):
    if f(x) > 0:
        x_new = x - (f(x)/misc.derivative(f, x))
    return x_new

def newton_iter(x, tol):
    error = abs(f(x))
    iterasjoner = 0
    while error > tol and iterasjoner < 10000:
        try:
            x = newton(x)
        except OverflowError:
            print("Kan ikke konvergere")
            break
        
        error = abs(f(x))
        iterasjoner += 1
        print(f"Antall iterasjoner: {iterasjoner}, error: {error}")
    print(f"Konvergerer etter {iterasjoner} iterasjoner")
    
newton_iter(1.2, 10e-6)
#print(newton(1.2))

and i keep getting:

 File "C:line 39, in <module>
    newton_iter(1.2, 10e-6)

  File "C: line 29, in newton_iter
    x = newton(x)

  File "C:, line 22, in newton
    return x_new

UnboundLocalError: local variable 'x_new' referenced before assignment

What am i doing wrong?


Solution

  • You do not define the variable in all cases. If f(x) is non-positive, you don't set it. You can't reference the value for return. You need to handle the other case:

    def newton(x):
        if f(x) > 0:
            x_new = x - (f(x)/misc.derivative(f, x))
        else:
            # Do something to set x_new
        return x_new