Integrating a set of ordinary differential equations (ODEs) given
initial conditions is another useful example. The function odeint
is available in SciPy for integrating a first-order vector differential
equation:
For example suppose it is desired to find the solution to the following
second-order differential equation:
First, convert this ODE into standard form by setting
and
Thus, the differential equation becomes
As an interesting reminder, if
commutes
with
under
matrix multiplication, then this linear differential equation has
an exact solution using the matrix exponential:
There are many optional inputs and outputs available when using odeint which can help tune the solver. These additional inputs and outputs are not needed much of the time, however, and the three required input arguments and the output solution suffice. The required inputs are the function defining the derivative, fprime, the initial conditions vector, y0, and the time points to obtain a solution, t, (with the initial value point as the first element of this sequence). The output to odeint is a matrix where each row contains the solution vector at each requested time point (thus, the initial conditions are given in the first output row).
The following example illustrates the use of odeint including the
usage of the Dfun option which allows the user to specify
a gradient (with respect to ) of the function,
.
>>> from scipy.integrate import odeint >>> from scipy.special import gamma, airy >>> y1_0 = 1.0/3**(2.0/3.0)/gamma(2.0/3.0) >>> y0_0 = -1.0/3**(1.0/3.0)/gamma(1.0/3.0) >>> y0 = [y0_0, y1_0] >>> def func(y, t): return [t*y[1],y[0]] >>> def gradient(y,t): return [[0,t],[1,0]] >>> x = arange(0,4.0, 0.01) >>> t = x >>> ychk = airy(x)[0] >>> y = odeint(func, y0, t) >>> y2 = odeint(func, y0, t, Dfun=gradient) >>> import sys >>> sys.float_output_precision = 6 >>> print ychk[:36:6] [ 0.355028 0.339511 0.324068 0.308763 0.293658 0.278806] >>> print y[:36:6,1] [ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806] >>> print y2[:36:6,1] [ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806]