我正在学习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'
答案 0 :(得分:2)
您忘了从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)
答案 1 :(得分:0)
您的derivative_formula
没有return
语句,其中python默认为return None
。因此,当您致电abs(derivative_estimate - V)
时,您实际上是从另一个NoneType
对象中减去V
对象(NoneType
)。
您需要的是derivative_formula
中的return语句:
def derivative_formula(x, h):
res = (fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h
return res