Differential equations in Python: Single time step
Question
I would like to be able to do something else in each time step during solving an ODE (using scipy's integrate). Is there a way to do so? Can I somehow write my own time loop and just call a single e.g. Runge-Kutta step by myself? Is there a routine in python or would I have to come up with my own? I think there must be one since odeint etc have to use such a function. So the question is, how do I access them?
So it should looking something along these lines:
from scipy.integrate import *
from pylab import *
def deriv(y, t):
a = -2.0
b = -0.1
return array([y[1], a*y[0]+b*y[1]])
time = linspace(0.0, 10.0, 1000)
dt = 10.0/(1000-1)
yinit = array([0.0005, 0.2])
for t in time:
# doSomething, write into a file or whatever
y[t] = yinit
yinit = RungeKutta(deriv, yinit, t, dt, varargs)
Solution
I now came along with this:
from pylab import *
from scipy.integrate import *
def RHS(t, x):
return -x
min_t = 0.0
max_t = 10.0
num_t = 1e2
grid_t = linspace(min_t, max_t, num_t)
grid_dt = (max_t - min_t)/(num_t - 1)
y = zeros(num_t, dtype=complex)
y[0] = complex(1.0, 0.0)
solver = complex_ode(RHS)
solver.set_initial_value(y[0], grid_t[0]).set_integrator('dopri5')
for idx in range(1, int(num_t)):
solver.integrate(solver.t + grid_dt)
y[idx] = solver.y[0]
In here I can do whatever I want during the integration.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow