int main(int argc, char **argv) { int i, N = 100; /* Number of nodes (discretization) */ double t0 = 0.0, y0 = 0.5; /* Initial conditions */ double h = 1.0/N; /* RK step */ double time, y; /* y (solution) at time - time */ FILE *fp; /* Open a file to write in the results */ /* One can store the results in vectors */ fp = fopen( "results.dat", "w" ); for(i = 0; i < N; i++){ eulerStep(f,t0,y0,h,i,&time,&y); /* rkFehlbergStep(f, fy, t0, y0, h, i, &time, &y); */ fprintf( fp, "%f %f\n", time, y ); t0 = time; y0 = y; } fclose(fp); return 0; }
/* * 打印通过欧拉法 */ void eulerPrint(OdeFormula f,real t0,real x0,real step,int n) { real t,x,h; t = t0; x = x0; h = step; printf("euler method,initial value t=%.4f x=%.4f step=%.4f\n",t0,x0,step); printf("%.4f\t|%.4f\n",t,x); for(int i=0;i<n;i++){ x = eulerStep(f,t,x,h); t+=h; printf("%.4f\t|%.4f\n",t,x); } }
/* * This is an entry point to the time integration. When things are fully * running we do a third level Adams-Bashforth scheme which requires knowing the * past three forcing evaluations. Since these are not available intitially, * the first few steps are lower order while we ramp up. */ void step() { if(iteration == 1) { eulerStep(); } else if(iteration == 2) { AB2Step(); } else { AB3Step(); } elapsedTime += dt; }
/* * 对三种方法比较进行比较 */ void comparePrint(OdeFormula f,real t0,real x0,real step,int n) { real t,x,h,mx,sx,A,tx; t = t0; tx = sx = mx=x = x0; h = step; A = f(t,x,INITIAL); printf("变量\t|欧拉法\t误差\t|中点法\t误差\t误差比\t|测试\t误差|公式法|\n"); for(int i=0;i<n;i++){ x = eulerStep(f,t,x,h); mx = midpointStep(f,t,mx,h); tx = testStep(f,t,tx,h); t+=h; sx = f(t,A,SOLVE); printf("%.4f\t|%.4f\t%.4f\t|%.4f\t%.4f\t%.4f\t|%.4f\t%.7f|%.4f|\n",t,x,sx-x,mx,mx-sx,fabs(mx-sx)/fabs(sx-x),tx,tx-sx,sx); } }
// Simulation step using interpolation void Sim::simStep() { int type = 2; float dt = 0.1f; t += dt; switch (type) { case 0: rightStep(); break; case 1: eulerStep(dt); break; case 2: semiImplicitEuler(dt); break; default: rungeKuttaStep(dt); // This fails after multiple collisions! } }