求一个用C++程序编写的四阶龙格库塔算法

来源:百度知道 编辑:UC知道 时间:2024/05/25 20:01:41
最好在明天下午3点之前。。。。。(一定要是能运行的)

#include<iostream>
using namespace std;

//f为函数的入口地址,x0、y0为初值,xn为所求点,step为计算次数
double Runge_Kuta( double (*f)(double x, double y), double x0, double y0, double xn, long step )
{
double k1,k2,k3,k4,result;
double h=(xn-x0)/step;

if(step<=0)
return(y0);

if(step==1)
{
k1=f(x0,y0);
k2=f(x0+h/2, y0+h*k1/2);
k3=f(x0+h/2, y0+h*k2/2);
k4=f(x0+h, y0+h*k3);
result=y0+h*(k1+2*k2+2*k3+k4)/6;
}
else
{
double x1,y1;

x1=xn-h;
y1=Runge_Kuta(f, x0, y0, xn-h,step-1);
k1=f(x1,y1);
k2=f(x1+h/2, y1+h*k1/2);
k3=f(x1+h/2, y1+h*k2/2);
k4=f(x1+h, y1+h*k3);
result=y1+h*(k1+2*k2+2*k3+k4)/6;
}

return(result);
}

int main()
{
double f(double x, double y);
double x0=0,y0=1;
double x,y,step;
long i;

step=0.1;
cout.precision(10);
//f