使用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");
}

原文链接: https://www.cnblogs.com/neoLin/p/10999688.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    使用C++,用四阶Runge-Kutta的方法来求解一阶常微分方程

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/296503

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午5:55
下一篇 2023年2月15日 下午5:56

相关推荐