我正在学习python,并且作为实践,我编写了一些代码来查找用户定义函数的派生函数。代码如下。
def fx(value, function):
x = value
return eval(function)
input_function = raw_input('Input your function using correct python syntax: ')
def derivative_formula(x, h):
(fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h
def derivative_of_x(x):
error = 0.0001
h = 0.1
V = derivative_formula(x, h)
h = h / 2
derivative_estimate = derivative_formula(x, h)
while abs(derivative_estimate - V) < error:
V = derivative_formula(x, h)
h = h / 2
derivative_estimate = derivative_formula(x, h)
return derivative_estimate
x1 = float(raw_input('Where do you want to calculate the derivative?'))
return derivative_of_x(x1)完整的错误代码如下
Traceback (most recent call last):
File "Derivative.py", line 25, in <module>
print derivative_of_x(x1)
File "Derivative.py", line 17, in derivative_of_x
while abs(derivative_estimate - V) - error:
TypeError: Unsupported operand type(s) for -: 'NoneType' and 'NoneType'发布于 2015-02-13 15:22:49
您忘记了从derivative_formula函数返回任何内容。尝试:
def derivative_formula(x, h):
return (fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h此外,如果您试图除以2h,您将需要一个额外的括号。
def derivative_formula(x, h):
return (fx(x - h, input_function) - fx(x + h, input_function)) / (2 * h)我想你想把这两个函数的调用倒过来。
def derivative_formula(x, h):
return (fx(x + h, input_function) - fx(x - h, input_function)) / (2 * h)发布于 2015-02-13 15:26:46
您的derivative_formula没有在python中默认为return None的return语句。因此,当您调用abs(derivative_estimate - V)时,您实际上是从另一个NoneType对象中减去一个NoneType对象(V)。
您需要的是derivative_formula中的返回语句
def derivative_formula(x, h):
res = (fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h
return reshttps://stackoverflow.com/questions/28502636
复制相似问题