Computational Physics - Department of Physics

(Axel Boer) #1
8.6 Physics examples 257

E 0 =^1

2

kx(t= 0 )^2 =^1
2
k.

and use this when checking the numerically calculated energy from the Runge-Kutta
iterations.


  1. The Runge-Kutta method is used to obtainxi+ 1 andvi+ 1 starting from the previous
    valuesxiandvi..

  2. When we have computedx(v)i+ 1 we upgradeti+ 1 =ti+h.

  3. This iterative process continues till we reach the maximum timetf= 2 π.

  4. The results are checked against the exact solution. Furthermore, one has to check
    the stability of the numerical solution against the chosen number of mesh pointsN.


8.6.1.1 Program to solve the differential equations for a sliding block

The program which implements the above algorithm is presented here, with a corresponding
http://folk.uio.no/mhjensen/compphys/programs/chapter08/cpp/program1.cpp
/*Thisprogramsolves Newton's equation for a block sliding on a
horizontal frictionless surface. The block is tied to a wallwith a
spring, and Newton's equation takes theformm d^2x/dt^2 =-kx with
k the spring tension and m the mass of theblock. The angular
frequency is omega^2 = k/m and we set it equal 1inthis example
program.
Newton's equation is rewritten as two coupled differential
equations, one for the position x and one for the velocity v
dx/dt = v and dv/dt = -x when we set k/m=1
We use therefore a two-dimensional array to represent x and v
as functions of t y[0] == x y[1] == v dy[0]/dt = v dy[1]/dt =
-x
The derivatives are calculated by the user defined function
derivatives.
The user has to specify the initial velocity (usually v_0=0)
the number of steps and the initial position. In the
programme below we fix the time interval [a,b] to [0,2*pi].

*/ #include <cmath> #include <iostream> #include <fstream>#include
<iomanip> #include "lib.h" using namespace std; // output file as
global variable ofstream ofile; // function declarations void
derivatives(double, double*, double*); void initialise ( double&,
double&, int&); void output( double, double*, double); void
runge_kutta_4(double*, double *, int, double, double, double*,
void (*)(double, double*, double*));
int main(int argc, char*argv[]){// declarations of variables
double*y,*dydt,*yout, t, h, tmax, E0; double initial_x,
initial_v; int i, number_of_steps, n; char*outfilename; // Read
in output file, abort if there are too few command-line arguments
if( argc <= 1 ){cout << "Bad Usage: " << argv[0] << " read also
output file on same line" << endl; exit(1);}else{
outfilename=argv[1];}ofile.open(outfilename); // this is the
number of differential equations n = 2; // allocate space in
Free download pdf