循环访问列表'TypeError: cannot unpack non-iterable object'时出错



我正在编写一个Python脚本,用SciPy的odeint求解某个微分方程。我刚刚在文档页面上复制了一个例子:

def pend(y,t,b,c):
theta, omega = y
dydt = [omega, -b*omega -c*np.sin(theta)]
return dydt
b = 0.25
c = 5.0
y0 = [np.pi-0.1,0.0]
t = np.linspace(0,10,101)
sol = odeint(pend, y0, t, args = (b,c))
plt.plot(t,sol[:,1])
plt.plot(t,sol[:,0])

这一切都很好,但当我尝试使用Lotka-Volterra系统时,代码会崩溃:

def F(t,n,a,b,c,d):
x, y = n
deriv = [a*x-b*x*y,c*x*y-d*y]
return deriv
t = np.linspace(0,100,100)
a = 1.1
b= 0.4
c = 0.1
d = 0.4
n0 = [10,10]
sol = odeint(F,n0,t,args = (a,b,c,d))

这会返回一个TypeError

<ipython-input-14-ea2a41feaef2> in F(t, n, a, b, c, d)
1 def F(t,n,a,b,c,d):
----> 2     x, y = n
3     deriv = [a*x-b*x*y,c*x*y-d*y]
4     return deriv
5 
TypeError: cannot unpack non-iterable float object

有人能帮我看看我缺了什么吗?具体地说,如果第二个代码是用相同的结构编写的,为什么示例代码会起作用。谢谢

我假设这一行中传递的参数顺序不对:

sol = odeint(F,n0,t,args = (a,b,c,d))

不是吗:

sol = odeint(F,t,n0,args = (a,b,c,d))

或者,您可以将函数定义中的参数顺序交换为:

def F(n,t,a,b,c,d):

相关内容

最新更新