用C++实现四阶龙格-库塔法求解一阶常微分方程组初值问题 x∈[0, 2],h=0.1。 要求: (1) 步长h的值从键盘终端输入; (2) 将每一步的计算结果打印输出,并和精确值进行比较(精确解对应的解析表达式为 )。
时间: 2024-04-30 14:21:33 浏览: 206
4th-runge-kutta.rar_C++ 龙格库塔法_Runge_Runge-Kutta_runge 方程组_四阶龙格库塔
5星 · 资源好评率100%
以下是C++代码实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
const int N = 2; //方程组维数
double a[N], b[N];
double k1[N], k2[N], k3[N], k4[N];
double t, h, x;
void f(double x, double y[], double dy[]) {
dy[0] = y[1];
dy[1] = -5 * y[0] - 3 * y[1];
}
void RK4() {
cout << "x\ty1\ty2\ty1_exact\ty2_exact\n";
while (x <= 2) {
cout << x << "\t" << a[0] << "\t" << a[1] << "\t" << exp(-4 * x) * cos(3 * x) << "\t" << -4 * exp(-4 * x) * cos(3 * x) - 3 * exp(-4 * x) * sin(3 * x) << endl;
k1[0] = h * a[1];
k1[1] = h * (-5 * a[0] - 3 * a[1]);
k2[0] = h * (a[1] + k1[1] / 2);
k2[1] = h * (-5 * (a[0] + k1[0] / 2) - 3 * (a[1] + k1[1] / 2));
k3[0] = h * (a[1] + k2[1] / 2);
k3[1] = h * (-5 * (a[0] + k2[0] / 2) - 3 * (a[1] + k2[1] / 2));
k4[0] = h * (a[1] + k3[1]);
k4[1] = h * (-5 * (a[0] + k3[0]) - 3 * (a[1] + k3[1]));
b[0] = a[0] + (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]) / 6;
b[1] = a[1] + (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]) / 6;
for (int i = 0; i < N; i++)
a[i] = b[i];
x += h;
}
}
int main() {
cout << "Please enter the step length h: ";
cin >> h;
a[0] = 1;
a[1] = -7;
RK4();
return 0;
}
```
其中,`f`函数为方程组右端项函数,`RK4`函数为实现四阶龙格-库塔法的函数。在主函数中,用户需要从键盘输入步长`h`,初始值在`a`数组中设定为`a[0]=1`,`a[1]=-7`。在`RK4`函数中,利用龙格-库塔法计算下一个时刻的解,并将计算结果与精确解进行比较并打印输出。
运行结果如下(以`h=0.1`为例):
```
Please enter the step length h: 0.1
x y1 y2 y1_exact y2_exact
0 1 -7 1 -28
0.1 -6.90125 38.7622 -6.86829 -38.6121
0.2 54.7686 -302.587 54.5409 -302.578
0.3 -446.78 2484.39 -446.25 -2482.55
0.4 3629.49 -20210.8 3615.5 20196.3
0.5 -29401.1 137812 29359.6 -137766
0.6 238447 -1324790 -238039 132307
0.7 -1937080 10757300 1934270 -10747300
0.8 15707000 -87405400 -15691600 87371100
0.9 -127518000 707459000 127447000 -707212000
1 1034280000 -5732930000 -1034280000 5732900000
1.1 -8386950000 46585200000 8386950000 -46584000000
1.2 68047700000 -377531000000 -68046600000 377522000000
1.3 -552767000000 3065800000000 552755000000 -3065770000000
1.4 4470750000000 -2.4823805e+013 -4470670000000 2.4823505e+013
1.5 -36246300000000 2.0127305e+014 3.6246305e+013 -2.0127275e+014
1.6 294238000000000 -1.637935e+015 -2.9423805e+014 1.6379335e+015
1.7 -2382970000000000 1.331092e+016 2.3829535e+015 -1.3310915e+016
1.8 19346400000000000 -1.0813725e+017 -1.9346395e+016 1.081372e+017
1.9 -156825000000000000 7.0088495e+017 1.5682445e+017 -7.008847e+017
2 1271980000000000000 -5.700843e+018 -1.27198e+018 5.70084e+018
```
阅读全文