python - 微分方程不支持的操作数类型
问题描述
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)
谢谢
解决方案
我不是专家,但括号与可调用函数密切相关,因此 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。希望这可以帮助。
推荐阅读
- android - 如何模糊像 WhatsApp 一样展开的折叠工具栏图像?
- scala - K => Ordered[K] 没有可用的隐式视图。涉及默认参数的应用程序发生错误
- multithreading - 为什么非守护线程完成后守护线程正在执行?
- html - 如何使页脚具有固定位置
- python - 即使位置被占用,代码也会通过并运行下一行..井字游戏
- c# - 我可以覆盖正在使用的文件吗?(C#)
- android - 实体中不存在主键引用的房间
- javascript - 在 javascript 中布局对象的最高效方式
- c++ - c ++在运行时修复库中的错误字符串
- oracle - 如何使用 Oracle SQL Developer 连接到在 docker 中运行的 Oracle 12c?