#include<stdlib.h>
#include<stdio.h>
/*n表示几等分,n+1表示他输出的个数*/
int RungeKutta(double y0,double a,double b,int n,double *x,double *y,int style,double (*function)(double,double))
{
double h=(b-a)/n,k1,k2,k3,k4;
int i;
// x=(double*)malloc((n+1)*sizeof(double));
// y=(double*)malloc((n+1)*sizeof(double));
x[0]=a;
y[0]=y0;
switch(style)
{
case 2:
for(i=0;i<n;i++)
{
x[i+1]=x[i]+h;
k1=function(x[i],y[i]);
k2=function(x[i]+h/2,y[i]+h*k1/2);
y[i+1]=y[i]+h*k2;
}
break;
case 3:
for(i=0;i<n;i++)
{
x[i+1]=x[i]+h;
k1=function(x[i],y[i]);
k2=function(x[i]+h/2,y[i]+h*k1/2);
k3=function(x[i]+h,y[i]-h*k1+2*h*k2);
y[i+1]=y[i]+h*(k1+4*k2+k3)/6;
}
break;
case 4:
for(i=0;i<n;i++)
{
x[i+1]=x[i]+h;
k1=function(x[i],y[i]);
k2=function(x[i]+h/2,y[i]+h*k1/2);
k3=function(x[i]+h/2,y[i]+h*k2/2);
k4=function(x[i]+h,y[i]+h*k3);
y[i+1]=y[i]+h*(k1+2*k2+2*k3+k4)/6;
}
break;
default:
return 0;
}
return 1;
}
double function(double x,double y)
{
return y-2*x/y;
}
//例子求y'=y-2*x/y(0<x<1);y0=1;
/*
int main()
{
double x[6],y[6];
printf("用二阶龙格-库塔方法\n");
RungeKutta(1,0,1,5,x,y,2,function);
for(int i=0;i<6;i++)
printf("x[%d]=%f,y[%d]=%f\n",i,x[i],i,y[i]);
printf("用三阶龙格-库塔方法\n");
RungeKutta(1,0,1,5,x,y,3,function);
for(i=0;i<6;i++)
printf("x[%d]=%f,y[%d]=%f\n",i,x[i],i,y[i]);
printf("用四阶龙格-库塔方法\n");
RungeKutta(1,0,1,5,x,y,4,function);
for(i=0;i<6;i++)
printf("x[%d]=%f,y[%d]=%f\n",i,x[i],i,y[i]);
return 1;
}