手撕求解偏微分方程——龙格库塔法
1 | %reset -f |
四阶RK法:
首先将方程转化为标准形式:
$$\begin{cases}\dot{\mathrm{y_1}}&=\mathrm{f_1}\left(\mathrm{y_1},\cdots,\mathrm{y_n},\mathrm{t}\right)\\ &\vdots\\ \dot{\mathrm{y_n}}&=\mathrm{f_n}\left(\mathrm{y_1},\cdots,\mathrm{y_n},\mathrm{t}\right)\end{cases}$$
$$\begin{cases}
h_m =& t_{m+1} - t_m \\
k_{1i}^m =& f_i(y_1^m, \cdots, y_i^m, \cdots, y_n^m, t_m) \\
k_{2i}^m =& f_i(y_1^m, \cdots, y_i^m + \frac{h_m}{2}k_{1i}^m, \cdots, y_n^m, t_m + \frac{h_m}{2}) \\
k_{3i}^m =& f_i(y_1^m, \cdots, y_i^m + \frac{h_m}{2}k_{2i}^m, \cdots, y_n^m, t_m + \frac{h_m}{2}) \\
k_{4i}^m =& f_i(y_1^m, \cdots, y_i^m + h_m k_{3i}^m, \cdots, y_n^m, t_m + \frac{h_m}{2}) \\
y_i^{m+1} =& y_i^m + \frac{h_m}{6}(k_{1i}^m + 2k_{2i}^m + 2k_{3i}^m + k_{4i}^m)
\end{cases}$$
例,解如下:
$$\begin{aligned}&\cfrac{dx}{dt}=x+2y\\ &\cfrac{dy}{dt}=3x+2y,\end{aligned}\qquad\begin{cases}x(0)=6\\ y(0)=4\end{cases}$$
1 | import numpy as np |
$$\begin{cases}\dot{\mathrm{y_1}}&=\mathrm{f_1}\left(\mathrm{y_1},\cdots,\mathrm{y_n},\mathrm{t}\right)\\ &\vdots\\ \dot{\mathrm{y_n}}&=\mathrm{f_n}\left(\mathrm{y_1},\cdots,\mathrm{y_n},\mathrm{t}\right)\end{cases}$$
$$\begin{cases}
h_m =& t_{m+1} - t_m \\
k_{1i}^m =& f_i(y_1^m, \cdots, y_i^m, \cdots, y_n^m, t_m) \\
k_{2i}^m =& f_i(y_1^m, \cdots, y_i^m + \frac{h_m}{2}k_{1i}^m, \cdots, y_n^m, t_m + \frac{h_m}{2}) \\
k_{3i}^m =& f_i(y_1^m, \cdots, y_i^m + \frac{h_m}{2}k_{2i}^m, \cdots, y_n^m, t_m + \frac{h_m}{2}) \\
k_{4i}^m =& f_i(y_1^m, \cdots, y_i^m + h_m k_{3i}^m, \cdots, y_n^m, t_m + \frac{h_m}{2}) \\
y_i^{m+1} =& y_i^m + \frac{h_m}{6}(k_{1i}^m + 2k_{2i}^m + 2k_{3i}^m + k_{4i}^m)
\end{cases}$$
1 | for m in range(nt-1): |
1 | from matplotlib import pyplot as plt |
[<matplotlib.lines.Line2D at 0x2448def2d90>]