实现常微分方程组的循环

时间:2014-03-02 05:29:13

标签: python scipy ode differential-equations

我是新来的,使用Python。我正在研究常微分方程系统的数值解法。 我的问题:我需要在函数内部实现一个循环。之后,我需要集成该函数(odeint),但它不起作用。

这是没有循环的(工作)代码:

from scipy.integrate import odeint
from pylab import * # for plotting commands
def deriv(y,t): # return derivatives of the array y
    a = 2.0
    return array([ y*a*(1-y/10)]) 
time = linspace(0,500,1000)
yinit = 1 
y = odeint(deriv,yinit,time)
figure()
plot(time,y)
xlabel('t')
ylabel('y')
show()

这是非工作代码:

from scipy.integrate import odeint
from pylab import * # for plotting commands
def deriv(y,t): # return derivatives of the array y
    a = 2.0
    for i in range(0,10):
        return array([ y[i]*a*(1-y[i]/10) ]) 
time = linspace(0,500,1000)
yinit = linspace(1,1,10) 
y = odeint(deriv,yinit,time)
figure()
plot(time,y[:,0],time,y[:,1])
xlabel('t')
ylabel('y')
show()

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

使用具有4个以上维度或复杂函数的odeint的文档和示例实际上相当稀疏。 5个(独立)Voltera-Lotka系统的总体维度为10的工作实现可能如下所示:

from scipy import zeros_like
from scipy.integrate import odeint
from pylab import * # for plotting commands

def deriv(y,t): # return derivatives of the array y
    a = 2.0
    b = 0.5 #0.1
    c = 0.1
    doty = zeros_like(y)
    for i in range(0,5):
        j=2*i   # this has no deep reason
        k=2*i+1 # just keeps notation short
        doty[j] = y[j]*a*(1-y[j]/10)-b*y[j]*y[k]
        doty[k] = b*y[j]*y[k]-c*y[k]

    return doty

time = linspace(0,500,1000)
yinit = linspace(1,1,10) 
y = odeint(deriv,yinit,time)
figure()
plot(time,y[:,0],time,y[:,1],time,y[:,5],time,y[:,8])
xlabel('t')
ylabel('y')
show()

答案 1 :(得分:0)

以下是已编辑的代码,您的语法已关闭:

from scipy.integrate import odeint
from pylab import * # for plotting commands
def deriv(y,t): # return derivatives of the array y
    a = 2.0
    b = 0.5 #0.1
    c = 0.1
    for i in range(0,10): #INSERT A COLON HERE
        return array([ y[i]*a*(1-y[i]/10)-b*y[i]*y[i], b*y[i]*y[i]-c*y[i] ]) #INDENT THIS
time = linspace(0,500,1000)
yinit = linspace(1,1,10)
y = odeint(deriv,yinit,time)
figure()
plot(time,y[:,0],time,y[:,1])
xlabel('t')
ylabel('y')
show()

你的错误在这里:

for i in range(0,10)
return array([ y[i]*a*(1-y[i]/10)-b*y[i]*y[i], b*y[i]*y[i]-c*y[i] ])

您应该在for语句后添加冒号,并缩进return

for i in range(0,10): #INSERT A COLON HERE
    return array([ y[i]*a*(1-y[i]/10)-b*y[i]*y[i], b*y[i]*y[i]-c*y[i] ]) #INDENT THIS
相关问题