gpt4 book ai didi

python - 我不断收到 "TypeError: unsupported operand type(s) for -: ' NoneType' 和 'NoneType' ”

转载 作者:行者123 更新时间:2023-12-01 04:50:57 27 4
gpt4 key购买 nike

我正在学习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'

最佳答案

您忘记从 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)

关于python - 我不断收到 "TypeError: unsupported operand type(s) for -: ' NoneType' 和 'NoneType' ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28502636/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com