试图用一块石头杀死两只鸟我决定编写一些代码,让我同时练习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
我是否需要在Derivative.py中声明input_function?我原本以为在newton_method.py中声明它就足够了。
答案 0 :(得分:0)
模块无权访问导入它们的模块的命名空间。想象一下导入Derivative.py
的10个模块。它会使用哪个input_function
? input_function
只是另一个值,应该是derivative_formula
的附加输入参数。