Solve ODE for Parameter Arrays (Python)
* I know this question is pretty simple, but I would like to know the best way to set up such a for loop in Python.
I already wrote a program to calculate and construct a solution to a 2nd order differential equation (this code is shown below).
I would like to know the best techniques for iterating this calculation for an array of f parameters (hence
). That is, so the graph shows the
data sets related to solutions as a function of
, each with a different value
Cheers for any ideas.
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 c1dot = -2*l*c - w0*w0*c + (f/m)*cos((gamma)*t)-alpha*c - beta*c*c*c 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()
Here is a graph showing the solution to this equation with respect to a single value
for an array of values
. I would like to quickly repeat this plot for an array of values
source to share
Here's one approach:
to accept a third argument, parameter
. The definition
def rhs(c, t, f): ...
with a loop
. In the loop, call
with an argument
give the value
as the third argument
. Save the results of each call
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)
For each value
, you now have a solution listed
To build them, you can place your call
in another loop
for ces in solutions: plot(t, ces[:, 0], 'b-')
source to share