rungekutta.cpp

来自「这事龙格-库塔解围分方程算法实例」· C++ 代码 · 共 50 行

CPP
50
字号
#include <iostream.h>
#include <iomanip.h>
#include <math.h>

double differential(double x,double y)
{
	return y-2*x/y;
}

void rungeKutta(double x0,double x1,double y0,double h,double (*f)(double x,double y))
//Euler's upgrading differential method
{
	double x,y;		//node and differential value
	double k1,k2,k3,k4;		//average gradient
	int i=0;

	cout<<setw(2)<<" i"<<setw(12)<<" x"<<setw(13)<<" y"<<endl;
	for(int j=0;j<27;j++)
		cout<<'-';
	cout<<endl;
	cout<<setw(2)<<i<<setw(12)<<x0<<setw(13)<<y0<<endl;
	cout<<setprecision(7);
	do
	{
		i++;
		
		k1=f(x0,y0);
		x=x0+h*0.5;
		k2=f(x,y0+h*k1*0.5);
		k3=f(x,y0+h*k2*0.5);
		x=x0+h;
		k4=f(x,y0+h*k3);

		y=y0+h*(k1+2*k2+2*k3+k4)/6;
				
		cout<<setw(2)<<i<<setw(12)<<x<<setw(13)<<y<<endl;
		x0=x;
		y0=y;
	}while(x<x1);
	for(j=0;j<27;j++)
		cout<<'-';
	cout<<endl;
}


void main()
{
	cout<<"Runge-Kutta's Differential method"<<endl;
	rungeKutta(0,1,1,0.2,differential);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?