// Appendix D.1 (p121) of Klein and Godunov Introductory Computational Physics // program to calculate the mass on a spring problem. //m=k=1; therefore a=-x //with the simple Euler method //ak 9/7/00 //all in double precision //small adjustments isv Jan. 2017 #include #include #include #include #include using namespace std; int main (int argc, char **argv) { int n; // number of steps double v; //the velocity double vinit= 5.;// initial velocity double x;// the x-value double xinit= 0.;// initial position double energy; // the energy from mv**2/2+kx**2/2 double step; //the step size for the euler method double t=0.;; //the time if (argc != 3) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(EXIT_FAILURE); } n = atoi(argv[1]); step= atof(argv[2]); int i = 0;//the loop counter // initial conditions t=0; v=vinit; x=xinit; energy=0.5*xinit*xinit + 0.5*vinit*vinit; cout << t << " " << x << " " << v << " " << energy << endl; while(i < n) //make n steps { v=v-step*x; //calculate the forward velocity x=x+step*v; //calculate the forward position energy=pow(x,2)/2.+pow(v,2)/2.; //energy conservation t=t+step; i=i+1; cout << t << " " << x << " " << v << " " << energy << endl; } }