通过牛顿方法找到根并将其称为解决一般方程的函数

时间:2016-05-22 05:02:17

标签: python newtons-method

我已经为牛顿方法编写了这个函数

#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

请帮我修复错误,哎呀

1 个答案:

答案 0 :(得分:1)

您的变量未在其使用范围中定义:

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 * tolerance
    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