通过牛顿法求根并调用它求解一般方程的函数

function to find roots through Newton's method and calling it to solve general equation

我为牛顿法写了这个函数

#root_Newton.py

def root_newton ( f, df, guess, tolerance = 1.0e-6):
    dx = 2 * tolerance
    while dx > tolerance:
        x1 = x - f(x)/df(x)
        dx = abs (x - x1)
        x = x1
    return x

并调用它来求解二次方程

from math import *
from root_Newton import root_newton

def function(x):
    x = x**2 - 1*x -6
    return x
def derivative(dx):
    dx = 2*x - 1 
    return dx

func = root_newton (function  , derivative , 1.7)

print  'Found f(x) =0 at x = %0.8f +/- %0.8f' % ( func , tolerance)

出现错误

File "quadfromnewtonsroot.py", line 11, in <module>
    func = root_newton (function  , derivative , 1.7)
  File "/home/trina/Pictures/python/root_Newton.py", line 4, in root_newton
    x1 = x - f(x)/df(x)
UnboundLocalError: local variable 'x' referenced before assignment

请帮我修正错误,谢谢

您有一些变量未在它们使用的范围内定义:

def root_newton (f, df, guess, epsilon=1.0e-6):
    """ calculates the root of the given equation
    to within epsilon, using Newton's method
    returns the root if found
    """
    dx = 2 * epsilon
    x = guess               #<--- your need to initialize x to the value of guess
    while dx > epsilon:
        x1 = x - f(x)/df(x)
        dx = abs(x - x1)
        x = x1
    return x

def function(x):
    """Evaluates the function at x
    returns the value found
    """
    return x**2 - 1*x - 6

def derivative(x):
    """Evaluates the derivative at x
    returns the value found
    """
    return 2*x - 1

root = root_newton(function, derivative, 1.7)
epsilon = 1.0e-6    #<--- you need to define epsilon in this scope to be able to print it

print 'Found f(x) = 0 at x = %0.8f +/- %0.8f' % (root, epsilon)

输出

Found f(x) = 0 at x = 3.00000000 +/- 0.00000100