问题
I want to use scipy.integrate.ode
solver. I can define the callable function f
only as an array of discrete points (because it depends on results of integration from previous iterations). But from the documentation it seems that the integrator expects the callable to be a continuous function. I suppose some sort of interpolation needs to be done. Can the solver deal with this on its own, or do I need to write some interpolation routine? Is there some scipy documentation/tutorial that explains it?
回答1:
Yes, the callable needs to be a function which returns the derivative for any value that is provided to the function. If you have a function interp
which does the interpolation, you can define the callable as follows:
f = lambda t,y: interp(y, yvalues, fvalues)
In case your system is scalar, you can use the numpy.interp
function like in the following example:
import numpy
from scipy import integrate
yvalues = numpy.arange(-2,3,0.1)
fvalues = - numpy.sin(yvalues)
f = lambda t,y: numpy.interp(y, yvalues, fvalues)
r = integrate.ode(f)
r.set_initial_value(1)
t1 = 10
dt = 0.1
while r.successful() and r.t < t1:
r.integrate(r.t+dt)
print r.t, r.y
For a multidimensional system, interpolation is very involved. If there is any way to compute the derivative on the fly at a given point, it is probably easier to implement than using interpolation.
As unutbu points out in the comment, you will get a wrong solution for large enough time with a chaotic system if you interpolate. However, since the same is true for any numerical solution algorithm, it is hard to do anything about it.
来源:https://stackoverflow.com/questions/14114596/ode-integration-with-discretized-values