使用C++,用四阶Runge-Kutta的方法来求解一阶常微分方程
作者:互联网
#include <iostream>
using namespace std;
/*
dy/dx = y - 2x/y, 0< x <= 1
步长h = 0.2
*/
const double h = 0.2;
//待求解的一节常微分方程,dy/dx = f_x
double f_x(double x, double y)
{
return (y - 2 * x / y);
}
int main() {
double k[5];//其实k[0]没有用到,为了看起来更简洁
double y[6];
y[0] = 1;
double x[6] = { 0.0,0.2, 0.4, 0.6, 0.8, 1.0 };
//计算出的是y[i+1]所以到 i = 5就行了。
for (int i = 0; i < 5; ++i) {
k[1] = f_x(x[i], y[i]);
k[2] = f_x(x[i] + h / 2, y[i] + h / 2 * k[1]);
k[3] = f_x(x[i] + h / 2, y[i] + h / 2 * k[2]);
k[4] = f_x(x[i] + h, y[i] + h * k[3]);
y[i + 1] = y[i] + h / 6*(k[1] + 2 * k[2] + 2 * k[3] + k[4]);
}
for (int i = 0; i < 6; ++i) {
cout << y[i] << endl;
}
system("pause");
}
标签:Kutta,std,四阶,2x,C++,dx,using 来源: https://www.cnblogs.com/neoLin/p/10999688.html