*我知道这个问题很简单,但我想知道在Python中设置这样一个for循环的最佳方法。
我已经编写了一个程序来计算和绘制一个二阶微分方程的解(下面给出了这个代码)。
我想知道对f参数数组(因此是f_array
)重复此计算的最佳方法。也就是说,图中显示了20
数据集,这些数据作为t
的函数引用了解决方案,每个f
的值都不同。
为任何想法干杯。
from pylab import *
from scipy.integrate import odeint
#Arrays.
tmax = 100
t = linspace(0, tmax, 4000)
fmax = 100
f_array = linspace(0.0, fmax, 20)
#Parameters
l = 2.5
w0 = 0.75
f = 5.0
gamma = w0 + 0.05
m = 1.0
alpha = 0.15
beta = 2.5
def rhs(c,t):
c0dot = c[1]
c1dot = -2*l*c[1] - w0*w0*c[0] + (f/m)*cos((gamma)*t)-alpha*c[0] - beta*c[0]*c[0]*c[0]
return [c0dot, c1dot]
init_x = 15.0
init_v = 0.0
init_cond = [init_x,init_v]
ces = odeint(rhs, init_cond, t)
s_no = 1
subplot(s_no,1,1)
xlabel("Time, t")
ylabel("Position, x")
grid('on')
plot(t,ces[:,0],'-b')
title("Position x vs. time t for a Duffing oscillator.")
show()
下面是一个图,显示了对于一个f
值数组的t
值,这个方程的解决方案。我想要一种快速的方法来为f
值数组重复这个图。
发布于 2014-09-17 14:12:32
这里有一个方法:
修改rhs
以接受第三个参数,参数f
。rhs
的定义应该开始
def rhs(c, t, f):
...
使用一个f_array
循环在for
上迭代。在循环中,使用odeint
参数调用args
,以便odeint
将f
的值作为第三个参数给rhs
。将每次调用odeint
的结果保存在列表中。基本上,替换
ces = odeint(rhs, init_cond, t)
使用
solutions = []
for f in f_array:
ces = odeint(rhs, init_cond, t, args=(f,))
solutions.append(ces)
对于f
在f_array
中的每个值,您现在在solutions
列表中有了一个解决方案。
要绘制这些代码,您可以将plot
调用放到另一个for
循环中:
for ces in solutions:
plot(t, ces[:, 0], 'b-')
https://stackoverflow.com/questions/25891972
复制相似问题