Anda di halaman 1dari 2

dy/dx = -y, y(0) = 1

/* A Runge-Kutta Method for solving Differential Equations*/

/* dy/dt = -y(t), y(0)=1, 0<=x<=5, start h=0.1*/


 
#include <stdio.h>
 
#define dist 0.1 /* stepsize */
#define xf 5 /* max for x */
 
 
FILE *output; /* internal filename */
 
double rkutta( double x, double y, double h); /*Runge Kutta Function */
double F(double x, double y); /*Function derivative*/
 
main()
{
double x, y, h;
int n;
 
output=fopen("xydata.dat", "w"); /* External filename */
h=0.1;
y=1; /* Initial condition */
fprintf(output, "0\t%f\n", y);
 
for (n=0;dist*n<=xf;n++) /* The time loop */
{
x=n*dist;
y-=rkutta(x, y, dist);
 
fprintf (output, "%f\t%f\n", x, y);
}
 
fclose(output);
} /* End of main function*/
 
double rkutta(double x, double y, double h) /*Called on RK function*/
{
double yn, k1, k2, k3, k4;
double H = h/2.0;
 
k1 = (h*F(x, y));
k2 = (h*F(x+H, y+(k1/2)));
k3 = (h*F(x+H, y+(k2/2)));
k4 = (h*F(x+h, y+k3));
return(y+=(y+(k1+2*k2+2*k3+k4)*1/6));
}
 
 
double F(double x, double y) /*Called on derivative*/
{
return (y);
}

Anda mungkin juga menyukai