/* ************************************************************************ * ルンゲ・クッタ法による1次元運動方程式の解法 * * 投げ上げ * * t:時間、x :位置 --> x[0]、v:速度 --> x[1]、 * * dt:時間の刻み幅 * * t0、x0、v0:初期値 * * * ************************************************************************ */ #include #include #define N 2 /* 方程式の数 */ main() { void rungen(double t, double x[], double dt); double f(double t, double x[], int i); double t, x[N], v0, dt, h, xreal, xerror; int j; FILE *output; output = fopen("fall.dat","w"); /* fall.datにデータをセーブ */ printf("Input: v0\n"); scanf("%lf", &v0); printf("v0=%g\n", v0); printf("Input: dt\n"); scanf("%lf", &dt); printf("dt=%g\n", dt); t = 0; x[0] = 0.0; /* 初期位置 */ x[1] = v0; /* 初期速度 */ fprintf(output, "%f\t%f\n", t, x[0]); while(x[0] >= 0) { rungen(t, x, dt); t += dt; xreal=v0*t-0.5*9.8*t*t; /* 解析解 */ xerror=x[0]-xreal; /* 誤差=数値解-解析解 */ fprintf(output, "%f\t%f\t%f\t%e\n", t, x[0], xreal, xerror); } printf("data stored in fall.dat\n"); fclose(output); } /*-----------------------end of main program--------------------------*/ /* Runge-Kutta法 */ void rungen(double t, double x[], double dt) { double f(double t, double x[], int i); double h=dt/2.0, t1[N], t2[N], t3[N], /* Runge-Kutta法のための */ k1[N], k2[N], k3[N],k4[N]; /* 一時変数 */ int i; for (i=0; i