2016-05-22 7 views
-1

を解決するために、それを呼び出して、私はニュートン法ニュートン法による根を見つけるための機能と一般式

#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 

thnks

を修正してください
+3

を'root_newton'です。同じことが 'derivative' btwでも起こります。 –

+1

def def(dx):をdef def(x)に変更します。 –

答えて

1

あなたは、彼らが使用されていたスコープで定義されていなかった変数を持っていた:あなたはあなたがそれに何かを割り当てることはありませんまだ変数 'X'を使用している

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 
関連する問題