Skip to main content
 首页 » 编程设计

python之使用 scipy.integrate.odeint : "Result from function call is not a proper array of floats." 求解微分方程

2024年10月25日11虾米姐

我正在绘制这个非线性一阶微分方程的图形:

dv/dt + 3 v**2 + 2 = 0 

代码如下:

from scipy.integrate import odeint 
 
from matplotlib import pyplot as plt 
 
import numpy as np 
 
def diff(v, t): 
 
      return [v, -3*v*v - 2] 
 
t = np.arange(-1,1,0.01) 
 
v0 = 1 
 
f = odeint(diff, v0, t) 
 
plt.figure(figsize=(5,5)) 
 
plt.plot(t, f) 
 
plt.show() 

但是,这不起作用:

odepack.error: Result from function call is not a proper array of floats.

请您参考如下方法:

odeint routine期望第一个参数只计算导数:

func : callable(y, t0, …)
Computes the derivative of y at t0.

但是,您的函数 diff 返回一个 2 元素列表除了导数之外还包含解:

def diff(v, t): 
 
      return [v, -3*v*v - 2] 

要解决此问题,您只需从返回值中删除 v 并避免将其包装在列表中:

def diff(v, t): 
 
      return -3*v*v - 2