I will explain how to solve ordinary differential equations using Python.
OS / Python module version The OS used is Windows 10. The Python module version is:
console
> python --version
Python 3.4.3
> pip freeze
matplotlib==1.4.3
numpy==1.13.1+mkl
pandas==0.16.2
pyparsing==2.0.3
python-dateutil==2.4.2
pytz==2015.4
scipy==0.19.1
six==1.9.0
sample code Solve the following differential equation.
y'' = -y \\
Introduce the variable z. By increasing the variables, one second-order differential equation is considered as a simultaneous equation of two first-order differential equations.
y' = z \\
z' = -y \\
The initial conditions are $ t = 0, y_0 = 1, z_0 = 0 $. The solution is $ cos (t) $. Since the correct solution can be easily obtained, the error can be evaluated.
The following is a Python program that solves differential equations. Solve using scipy.integrate.ode.
test.py
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import ode
def f(t, v): # t, y:v[0], y'=z:v[1]
return [v[1], -v[0]] # y':return[0] y''=z':return[1]
v0 = [1.0, 0.0] # y0, y'0=z0
solver = ode(f)
solver.set_integrator(name="dop853")
solver.set_initial_value(v0)
tw = 10.0*2.0*np.pi
dt = tw / 1000;
t = 0.0
ts = []
ys = []
while solver.t < tw:
solver.integrate(solver.t+dt)
ts += [solver.t]
ys += [solver.y[0]]
plt.figure(0)
plt.plot(ts, ys)
plt.figure(1)
plt.plot(ts, np.cos(ts)-ys)
plt.show()
print(np.max(np.cos(ts)-ys))
I will do it.
console
> python .\test.py
When executed, the graph will be displayed.
The following graph is the solution of the differential equation. The graph of cos (t) is displayed for 10 cycles.
The following graph plots the error. As t increases, so does the error. The error is on the scale of $ 10 ^ {-15} $.
Recommended Posts