牛顿法收敛但我得到未绑定错误

Newton's Method to convergence but I get Unbound Error

我有一个任务,我必须找出 x_0 的某些值是否收敛,但是当我测试值超过 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))

我不断得到:

 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

我做错了什么?

并非在所有情况下都定义变量。如果 f(x) 是非正数,则不要设置它。您不能引用 return 的值。您需要处理另一种情况:

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