首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我一直得到一个“TypeError:-:'NoneType‘和'NoneType’的不支持的操作数类型”

我一直得到一个“TypeError:-:'NoneType‘和'NoneType’的不支持的操作数类型”
EN

Stack Overflow用户
提问于 2015-02-13 15:13:07
回答 2查看 593关注 0票数 1

我正在学习python,并且作为实践,我编写了一些代码来查找用户定义函数的派生函数。代码如下。

代码语言:javascript
复制
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)

完整的错误代码如下

代码语言:javascript
复制
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'
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-13 15:22:49

您忘记了从derivative_formula函数返回任何内容。尝试:

代码语言:javascript
复制
def derivative_formula(x, h):
    return (fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h

此外,如果您试图除以2h,您将需要一个额外的括号。

代码语言:javascript
复制
def derivative_formula(x, h):
    return (fx(x - h, input_function) - fx(x + h, input_function)) / (2 * h)

我想你想把这两个函数的调用倒过来。

代码语言:javascript
复制
def derivative_formula(x, h):
    return (fx(x + h, input_function) - fx(x - h, input_function)) / (2 * h)
票数 2
EN

Stack Overflow用户

发布于 2015-02-13 15:26:46

您的derivative_formula没有在python中默认为return Nonereturn语句。因此,当您调用abs(derivative_estimate - V)时,您实际上是从另一个NoneType对象中减去一个NoneType对象(V)。

您需要的是derivative_formula中的返回语句

代码语言:javascript
复制
def derivative_formula(x, h):
    res = (fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h
    return res
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28502636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档