【问题标题】:Unsupported Operand type for differentiation equation微分方程不支持的操作数类型
【发布时间】:2020-06-18 08:49:38
【问题描述】:
import math
import decimal

n=5
s=3.5*n -14

def float_range(start, stop, step):
  while start < stop:
    yield float(start)
    start += decimal.Decimal(step)

initial=list(float_range(-14, 15, s))

def diff(f, x):
    dx = 1e-6
    r1 = f(x + dx) - f(x)
    f_x = r1 / dx
    return float(f_x)

def sinc(x):
    if x==0 :
        return
    else :
        return math.sin(x)/x

def Dsinc(x):
    Dsinc=diff(sinc,x)
    return Dsinc

def nraphson(f, Df, x, dx) :
    x1= x - f(x)/Df(x)
    while abs(x1-x) < dx: 
        x=x1
    print(x1)

for x in initial :
    print(x, nraphson(sinc,Dsinc,x,1e-6)) 

为学校项目编写的代码。不能使用 Numpy,所有微分和牛顿方法都必须编码,而不是使用 numpy 函数。

有谁知道我为什么会得到: TypeError: unsupported operand type(s) for -: 'float' and 'NoneType' 在第 16 行 r1 = f(x + dx) - f(x)

谢谢

【问题讨论】:

  • sync 中有if x == 0: return,这意味着当x0 时,返回值将是None,这似乎是在您的程序中发生的。跨度>

标签: python python-3.x typeerror


【解决方案1】:

我不是专家,但括号与可调用函数密切相关,所以 python 试图运行一个由 f 表示的函数,在你的例子中是一个浮点数,参数为 x + dx。那会给你一个错误。但是,您显然正在做一个数学问题,因此需要乘法符号来告诉 python 括号表示乘法不使用这些参数调用此函数。这对我来说在 python shell 中有效:

def diff(f, x):
    dx = 1e-6
    r1 = f*(x + dx) - f*(x)
    f_x = r1 / dx
    return float(f_x)

返回有效,因为 float 是一个内置函数,而您定义了 f_x。希望这可以帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-17
    • 2017-07-15
    • 2020-02-29
    • 2011-03-08
    • 2016-11-28
    • 2020-12-04
    相关资源
    最近更新 更多