#include <iostream>// 定义微分方程 dy/dx = f(x, y)
double f(double x, double y) {return 2 * x + y;
}// 四阶Runge-Kutta方法求解微分方程
double rungeKutta(double x0, double y0, double h, double xn) {double x = x0;double y = y0;while (x < xn) {double k1 = h * f(x, y);double k2 = h * f(x + h / 2, y + k1 / 2);double k3 = h * f(x + h / 2, y + k2 / 2);double k4 = h * f(x + h, y + k3);y = y + (k1 + 2 * k2 + 2 * k3 + k4) / 6;x += h;}return y;
}int main() {double x0 = 0.0;double y0 = 1.0;double h = 0.1;double xn = 1.0;double result = rungeKutta(x0, y0, h, xn);std::cout << "The value of y at x = " << xn << " is: " << result << std::endl;return 0;
}
此程序定义了微分方程 dy/dx = 2x + y,并利用四阶Runge-Kutta方法求解微分方程在给定边界条件下的数值解。