求解参数数组的 ODE (Python) [英] Solve a ODE for arrays of parameters (Python)
问题描述
*我知道这个问题很简单,但我想知道在 Python 中设置这样一个 for 循环的最佳方法.
*I am aware that this question is quite simple but I would like to know the best way to set up such a for loop in Python.
我已经编写了一个程序来计算和绘制二阶微分方程的解(此代码如下).
I have written a program already to calculate and plot the solution to a 2nd order differential equation (this code is given below).
我想知道对 f 参数数组(因此是 f_array
)重复此计算的最佳方法.IE.以便该图显示 20
组数据,这些数据将解决方案作为 t
的函数,每组数据具有不同的 f
值.
I would like to know best methods for repeating this calculation for an array of f parameters (hence f_array
). I.e. so that the plot shows 20
sets of data referring to solutions as a function of t
each with a different value of 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
值数组重复这个图.
Here is a plot showing the solution to this equation regarding a single value of f
for an array of t
values. I would like a quick way to repeat this plot for an array of f
values.
推荐答案
这是一种方法:
修改rhs
以接受第三个参数,即参数f
.rhs
的定义应该开始
Modify rhs
to accept a third argument, the parameter f
. The definition of rhs
should begin
def rhs(c, t, f):
...
使用 for
循环遍历 f_array
.在循环中,使用 args
参数调用 odeint
,以便 odeint
给出 f
的值作为第三个参数rhs
.将每次调用 odeint
的结果保存在一个列表中.基本上,替换
Iterate over the f_array
with a for
loop. In the loop, call odeint
with the args
argument so that odeint
gives the value of f
as the third argument to rhs
. Save the results of each call to odeint
in a list. Basically, replace
ces = odeint(rhs, init_cond, t)
与
solutions = []
for f in f_array:
ces = odeint(rhs, init_cond, t, args=(f,))
solutions.append(ces)
对于 f_array
中 f
的每个值,您现在在 solutions
列表中有一个解决方案.
For each value of f
in f_array
, you now have a solution in the solutions
list.
要绘制这些,您可以将 plot
调用放在另一个 for
循环中:
To plot these, you could put your plot
call in another for
loop:
for ces in solutions:
plot(t, ces[:, 0], 'b-')
这篇关于求解参数数组的 ODE (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!