Created
September 30, 2013 17:55
-
-
Save nicoguaro/6767568 to your computer and use it in GitHub Desktop.
Solve and first order ODE system, the right hand side is given as a string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from numpy import * | |
from scipy import integrate | |
def ode(f, t0, tf, n_steps, X0): | |
""" | |
Solve an ODE in the time interval [t0, tf] using a number of steps given | |
by nsteps, with initial conditions X0. The differential equation is | |
written as a system of linear equations | |
x'_i = f(x_j) | |
where f is an array of strings that defines the functions, the components | |
of the vector X are denoted by X[k] (k = 1, 2, 3... N, being N the number | |
of equations). | |
""" | |
t = linspace(t0, tf, n_steps) | |
def dX_dt(X, t=0): return map(eval, f) | |
X = integrate.odeint(dX_dt, X0, t) | |
return t, X | |
## Example | |
from matplotlib import pyplot as plt | |
f = ["X[1]", "sin(X[0])"] | |
t, X = ode(f, 0, 10, 1000, [1.0, 0]) | |
plt.plot(t, X[:,0], t, X[:,1], '--') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment