2015-02-24 105 views
0

試圖用一塊石頭殺死兩隻鳥我決定寫一點代碼,讓我可以同時練習python和微積分。我有兩個獨立的文件,Derivative.py和newton_method.py(我知道我應該更好地正確命名我的文件)。從Derivatibe.py的文本如下導入函數時出現全局名稱錯誤

def fx(value, function): 
    x = value 
    return eval(function) 

def function_input(input): 
    function = str(input) 
    return function 

def derivative_formula(x, h): 
    return (fx(x - h, input_function) - fx(x + h, input_function))/(2.0 * h) 

def derivative_of_x(x): 
    error = 0.0001 
    h = 0.1 
    V = derivative_formula(x, h) 
    print V 
    h = h/2.0 
    derivative_estimate = derivative_formula(x, h) 
    while abs(derivative_estimate - V) < error: 
     V = derivative_formula(x, h) 
     h = h/2.0 
     derivative_estimate = derivative_formula(x, h) 
     print derivative_estimate 
    return derivative_estimate 

而且從newton_method.py文字是:

from Derivative import * 

input_function = function_input(raw_input('enter a function with correct python syntax')) 

E = 1 * (10 ** -10) 

guessx = float(raw_input('Enter an estimate')) 

def newton_method(guessx, E, function): 
    x1 = guessx 
    x2 = x1 - (fx(x1, input_function)/derivative_of_x(x1)) 
    while x2 - x1 < E: 
     x1 = x2 
     x2 = x1 - (fx(x1, input_function)/derivative_of_x(x1)) 
    return x2 

print "The root of that function is %f" % newton_method(guessx, E, input_function) 

錯誤:

Traceback (most recent call last): 
    File "newton_method.py", line 17, in <module> 
    print "The root of that function is %f" % newton_method(guessx, E,   input_function) 
    File "newton_method.py", line 11, in newton_method 
    x2 = x1 - (fx(x1, input_function)/derivative_of_x(x1)) 
    File "C:\Users\159micarn\Desktop\Python\Derivative.py", line 15, in derivative_of_x 
    V = derivative_formula(x, h) 
    File "C:\Users\159micarn\Desktop\Python\Derivative.py", line 10, in derivative_formula 
    return (fx(x - h, input_function) - fx(x + h, input_function))/(2.0 * h) 
NameError: global name 'input_function' is not defined 

我需要在衍生聲明函數input_function的.py?我原以爲在newton_method.py中聲明它就足夠了。

回答

0

模塊無權訪問導入它們的模塊的名稱空間。想象一下,導入Derivative.py的10個模塊。它會使用哪個input_functioninput_function只是另一個值,應該是derivative_formula的附加輸入參數。

相關問題