// 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=100; // number of steps double v[n+1]; //the forward value calculated double vinit= 5.;// initial velocity double x[n+1];// the forward x-value double xinit= 0.;// initial position double energy[n+1]; // the energy from mv**2/2+kx**2/2 double ti[n+1];//the array of times double step=0.1; //the step size for the euler method double time=0.;; //the time int i = 0;//the loop counter // initial conditions ti[i]=time; v[i]=vinit; x[i]=xinit; energy[i]=0.5*xinit*xinit + 0.5*vinit*vinit; cout << ti[i] << " " << x[i] << " " << v[i] << " " << energy[i] << endl; while(i < n) //make n steps { v[i+1]=v[i]-step*x[i]; //calculate the forward velocity x[i+1]=x[i]+step*v[i]; //calculate the forward position energy[i+1]=pow(x[i+1],2)/2.+pow(v[i+1],2)/2.; //energy conservation time=time+step; ti[i+1]=time; i=i+1; cout << ti[i] << " " << x[i] << " " << v[i] << " " << energy[i] << endl; } }