1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
#include<stdio.h>
#include <math.h>
#include<conio.h>
#define A 0
#define B 1
float F(float x0, float y0)
{
return (0.2*x0)+(y0*y0);
}
float Rung4(float x0, float y0, float h)
{
float k1 = F(x0,y0);
float k2 = F(x0+h/2,y0+k1/2);
float k3 = F(x0+h/2,y0+k2/2);
float k4 = F(x0+h/2,y0+k2/2);
float y1 = y0 + ( k1 + 2*k2 + 2*k3 + k4)/6;
/* printf("\n\n k1 = %.4lf ",k1);
printf("\n\n k2 = %.4lf ",k2);
printf("\n\n k3 = %.4lf ",k3);
printf("\n\n k4 = %.4lf ",k4);
printf("\n\n y(%.4lf) = %.3lf ",x0+h,y1);*/
return y1;
}
float Maks(float *y, float *y2, float n)
{
int i;
float Maks=fabs(y[0]-y2[0]);
for(i=1; i<n; i++)
if (fabs(y[i]-y2[2*i])>Maks)
Maks= fabs(y[i]- y2[2*i]);
return Maks;
}
void Rk4()
{
int n=10, i;
float h=(float)(B-A)/n, *x, *y, *x1, *y2, esp=0.001;
do
{
x=new float [n+1];
y=new float [n+1];
x1=new float [n*2+1];
y2=new float [n*2+1];
for (i=0; i<n; i++)
{
y[0]=0.1;
x[n]=B;
x[i]=A+i*h;
y[i+1]=Rung4(x[i], y[i], h);
}
n=2*n;
h=(float)(B-A)/n;
for (i=0; i<n; i++)
{
y2[0]=0.1;
x1[n]=B;
x1[i]=A+i*h;
y2[i+1]=Rung4(x1[i], y2[i], h);
}
}
while ((Maks(y, y2, n/2)/15)>=esp);
puts("Runge- Kutta 4th Order");
for (i=0; i<n; i++)
printf("x[%d]=%.2f y[%d]=%6f\n", i, x[i], i, y[i]);
}
int main ()
{
// clrscr ();
Rk4();
getch ();
return 0;
}
|