首页 > 解决方案 > 微分方程不支持的操作数类型

问题描述

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' in line 16 at r1 = f(x + dx) - f(x)

谢谢

标签: pythonpython-3.xtypeerror

解决方案


我不是专家,但括号与可调用函数密切相关,因此 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。希望这可以帮助。


推荐阅读