如何在Python的odeint中传递列表询问参数?

时间:2019-07-08 16:51:44

标签: python

我是Python的新手,我在绘制能源与时间的关系图。我想用不同的epsilon值绘制几个图。 epsl = [0,0.3,0.02,0.05]。有没有办法通过odeint传递不同的epsilon值列表并绘制图形?下面的代码显示epsl的一个值为0.05。

def position(x,t, epsl):
    dx = np.zeros(2)
    # E(t) = 1/2mv^2 + 1/2kx^2
    # E(t)_bar = x_bar^2 + v_bar^2
    ko = 1                         
    omega = 2         
    k = ko*(1-epsl*np.cos(omega*t))
    dx[0] = x[1]
    dx[1] = -k*x[0]
    return dx

# initial conditions
ic=[1,1]

# make a list for epsl values
epsl = 0.05 

#time points
t = np.linspace(0, 200, 100000)

#solve ODE
ksoln = odeint(position, ic, t, args=(epsl,))

# Energy
Kenergy=ksoln[:,0]**2+ksoln[:,1]**2 

plt.plot(t, Kenergy)
plt.xlabel('t')
plt.title('Energy')
plt.show()

1 个答案:

答案 0 :(得分:0)

您可以在一个图上绘制多条线。尝试这样的事情:

def position(x,t, epsl):
    dx = np.zeros(2)
    # E(t) = 1/2mv^2 + 1/2kx^2
    # E(t)_bar = x_bar^2 + v_bar^2
    ko = 1                         
    omega = 2         
    k = ko*(1-epsl*np.cos(omega*t))
    dx[0] = x[1]
    dx[1] = -k*x[0]
    return dx

# initial conditions
ic=[1,1]

# make a list for epsl values
epsls = [0, 0.3, 0.02, 0.05]

#time points
t = np.linspace(0, 200, 100000)

#solve ODE
ksolns = [odeint(position, ic, t, args=(epsl,)) for epsl in epsls]

# Energy
Kenergys = [ksoln[:,0]**2+ksoln[:,1]**2 for kslon in kslons]

[plt.plot(t, Kenergy) for Kenergy in Kenergys]
plt.xlabel('t')
plt.title('Energy')
plt.show()