Computational Physics using MATLAB®

Kevin Berwick

Page 1

Table of Contents
Preface........................................................................................................................................ 6 1. Uranium Decay....................................................................................................................... 7 3. The Pendulum ........................................................................................................................ 9 3.1 Solution using the Euler method ...................................................................................... 9 3.1.1 Solution using the Euler-Cromer method.................................................................... 10 3.1.2 Simple Harmonic motion example using a variety of numerical approaches ............. 11 3.2 Solution for a damped pendulum using the Euler-Cromer method. ............................ 16 3.3 Solution for a non-linear, damped, driven pendulum :- the Physical pendulum, using the Euler-Cromer method. ................................................................................................... 18 3.4 Bifurcation diagram for the pendulum ......................................................................... 24 3.6 The Lorenz Model .......................................................................................................... 26 4. The Solar System .................................................................................................................28 4.1 Kepler’s Laws ..................................................................................................................28 4.1.1 Ex 4.1 Planetary motion results using different time steps .........................................30 4.2 Orbits using different force laws .................................................................................... 35 4.3 Precession of the perihelion of Mercury. .................................................................... 40 4.4 The three body problem and the effect of Jupiter on Earth ..........................................48 4.6 Chaotic tumbling of Hyperion....................................................................................... 53 5. Potentials and Fields ........................................................................................................... 60 5.1 Solution of Laplace’s equation using the Jacobi relaxation method. ........................... 60 5.1.1 Solution of Laplace’s equation for a hollow metallic prism with a solid, metallic inner conductor. ............................................................................................................................ 63 5.1.2 Solution of Laplace’s equation for a finite sized capacitor ........................................ 66 5.1.3 Exercise 5.7 and the Successive Over Relaxation Algorithm....................................... 70 5.2 Potentials and fields near Electric charges, Poisson’s Equation .................................... 75 6. Waves ................................................................................................................................... 78 6.1 Waves on a string ........................................................................................................... 78 6.1.1 Waves on a string with free ends ................................................................................. 81 6.2 Frequency spectrum of waves on a string .....................................................................83 7. Random Systems .................................................................................................................. 87 7.1 Random walk simulation ................................................................................................ 87 7.1.1 Random walk simulation with random path lengths. ..................................................89 10. Quantum Mechanics .......................................................................................................... 91 10.2 Time independent Schrodinger equation. Shooting method. ...................................... 91 Kevin Berwick Page 2

10.5 Wavepacket construction ............................................................................................. 93 10.3 Time Dependent Schrodinger equation in One dimension. Leapfrog method. ........... 95 10.4 Time Dependent Schrodinger equation in two dimensions. Leapfrog method. .......... 99

Kevin Berwick

Page 3

......... Results from Physical pendulum.........Simulation of Earth orbit........................002.......................................... Orbit for a force law with β=2.......Motion of Hyperion...... Simple Pendulum: Euler ...........................2 .................................... The time step is 0................................... using the Euler-Cromer method..............................001 years......... 10 Figure 4........................... 32 Figure 17.............................. 2500 points and Runge Kutta method .. The Runge Kutta Method is used here .. 40 Figure 23.. Simulation of solar system containing Jupiter and Earth.. Jupiter mass is 1000 X actual value...............................................Simulation of solar system containing Jupiter and Earth................................................. 66 Kevin Berwick Page 4 ......... using the Euler-Cromer method...............................50 Figure 26... 59 Figure 30...... 37 Figure 21... Uranium decay as a function of time ...................................... ............. Simulation of solar system containing Jupiter and Earth ....... using the Euler-Cromer method........ The initial velocity in the y direction was 5 HU/Hyperion year..............05 .................... Calculated precession rate of Mercury ............ ignoring perturbation of the Sun.05 . Equipotential surface for geometry depicted in Figure 5.... 62 Figure 31.................. This gave a circular orbit.........5 19 Figure 7............................. F_drive =0...... F_drive =0...................................... 45 Figure 24.....................002....... 23 Figure 12.......... ............................................... 31 Figure 16........ The initial velocity in the y direction was 1 HU/Hyperion year.....Euler Method ................................ Results from Physical pendulum. This gave a circular orbit........ npoints=2500.............. time step is 0................... 9 Figure 3............. time step is 0....... 21 Figure 10............... Results from Physical pendulum...............2 ............... 29 Figure 15.................001 years... 25 Figure 13........ Orbit for a force law with β=2............................................... initial y velocity of 8........................5.............. .........20 Figure 8....... Simple Pendulum . 33 Figure 18.. The time step is 0............. Bifurcation diagram for the pendulum ...............Results from Physical pendulum................... 35 Figure 20....... ................ 56 Figure 29.......... 17 Figure 6.... Note from the results that the tumbling is not chaotic under these conditions.......... dt is 0...... time step is 0..Cromer method........Table of Figures Figure 1........... F_Drive=1................ Runge Kutta and Matlab ODE45 solver. initial y velocity of 4....... F_drive =1.........................................2 .....................................8 Figure 2. .................................. .............................................Equipotential surface for hollow metallic prism with a solid metallic inner conductor held at V=1....... Simulation of Earth orbit...... Orbit for a force law with β=3.............................. 39 Figure 22................... Orbit orientation as a function of time ............ .. F_Drive=1..... F_Drive =1... Euler Cromer................................................. ........ using the Euler-Cromer method........... Jupiter mass is 10 X actual value. 15 Figure 5................ Note from the results that the tumbling is chaotic under these conditions..............Results from Physical pendulum................. initial y velocity of 4............................2 ..........5 21 Figure 9............ 27 Figure 14.............................. 22 Figure 11.................. ...................................... . Poincare section (Strange attractor) Omega as a function of theta.......... 52 Figure 28............ Variation of z as a function of time and corresponding strange attractor ................ using the Euler-Cromer method....... Simulation of Earth orbit with time step of 0............ Simple pendulum solution using Euler................ Simulation of Earth orbit........................... 47 Figure 25........ 33 Figure 19....Motion of Hyperion......................... Increase resolution with npoints=15000..............05..... Simulation of Earth orbit around the Sun ................Plot for an initial y velocity of 8...... 51 Figure 27....................... The damped pendulum using the Euler-Cromer method .....2 in the book .........

............ Wavepacket reflection from potential wall at x=0........................ 69 Figure 33..............................C=10.......Number of iterations required for SOR method vs L for a simple capacitor.. Average of 500 walks.. k_0=40...... The plot on the right compares the numerical and analytical (as obtained from Coulomb’s Law). Values used for initial wavepacket were x_0=0... y_0=0.................4.............. ................. sigma_squared=0.........................001...... 69 Figure 34...... The wall(s) of the box are at x=(-)1..................... k_0=500.....................................00001......... Signal excited with Gaussian pluck centred at the middle of the string and the displacement 5% from the end of the string was recorded......5.................................98 Figure 45. The potential was V=0 for x<0...................................... . ...........6.5. 74 Figure 37.5 and V=-1e3 for x>0......... x0=0...25............005.........98 Figure 46......... The potential was V=0 for x<0............................. 74 Figure 36......... ..................... ........................... Analytical value is 1...........6.................. Values used for initial wavepacket were x_0=0. Average of 500 walks......Wavepacket reflection from potential cliff at x=0....... delta_t=0..................... Waves propagating on a string with fixed ends .......... Simulation used delta_x=1e-3. 103 Kevin Berwick Page 5 . Simulation used delta_x=0........... 102 Figure 47.......... 79 Figure 39.... Values used for initial wavepacket were x_0=0......5 and V=1e3 for x>0..5..... ... sigma_squared=1e-3.... The Jacobi relaxation method was used ......... 77 Figure 38.......6...... 88 Figure 41......... delta_t=5e-8................... delta_t=5e-8........ ...4............. 94 Figure 44.....6...........6 and V=1e6 for x>0.. The convergence criterion was that the simulation was halted when the difference in successively calculated surfaces was less than 10-5 per site..........233............... Wavefunctions are not normalised... Step length = random value betwen +/-1..................... Equipotential contours near a finite sized capacitor.............C=10.Number of iterations required for Jacobi method vs L for a simple capacitor..... Simulation used delta_x=1e-3.Equipotential surface in region of a simple capacitor as calculated using the SOR code for a 60 X 60 grid............ .......Equipotential surface for a finite sized capacitor.. .C=10.. The convergence criterion was that the simulation was halted when the difference in successively calculated surfaces was less than 10-5 per site.............. .................. The convergence criterion was that the simulation was halted when the difference in successively calculated surfaces was less than 10-5 per site..................................................... Wavepacket reflection from potential wall at x=0............ Composition of wavepacket.......01.................... . Time progresses left to right............... Equipotential surface near a point charge at the center of a 20X20 metal box.......... The potential was V=0 for x<0......................... x^2 as a function of step number..... Calculated wavefunction using the shooting method. sigma_squared=1e-3.......00001....... Step length = 1.... ...... Signal from a vibrating string and Power spectrum.......................... delta_t=0.... Also shown is a linear fit to the data............... The potential was V=0 for x<0.......... y_0=0...... sigma_squared=0. 73 Figure 35.25........................ . x^2 as a function of step number.................... 90 Figure 42.......86 Figure 40. Simulation used delta_x=0................ 93 Figure 43......... Wavepacket reflection from potential cliff at x=0.... Values used for initial wavepacket were x_0=0.......................................Figure 32......... ko = 500... Also shown is a linear fit to the data........5...... k_0=500.......6 and V=-1e6 for x>0..........................................4..5. k_0=40....5................005....... sigma^2=0................. The value of Vo used was 1000 giving ground-state energy of 1..........23......... Time progresses left to right.01........C=10............

Since then. Any errors are. in the library here in the Dublin Institute of Technology in early 2012. and their enthusiasm for the project when initially proposed was very encouraging. ‘Computational Physics’. USA. The Dublin Institute of Technology has existing links with Purdue University since. I would like to thank the School of Electronics and Communications Engineering at the Dublin Institute of Technology for affording me the opportunity to write this book. Although I was only looking for one. deadlines loomed. I had started to use MATLAB® for teaching several other subjects around this time. my fault entirely. I travelled to Purdue for two weeks in Autumn 2012 to accelerate the completion of this personal project. They provided lot of useful advice on the physics. Suggestions for improvements. I hadn’t looked at using numerical methods since leaving College almost a quarter century ago. The applications were particularly well chosen and interesting.ie. I had a quick look at the Contents page and decided it was worth a more detailed examination. Nick Giordano and Hisao Nakanishi from the Department of Physics at Purdue must be first on the list. it offers a joint Master's Degree with Purdue in Sustainability. I would like to thank my family. Department of Education and the European Commission's Directorate General for Education and Culture for funding the Atlantis Programme. and is used in almost every Engineering School on Earth.berwick@dit. together with UPC Barcelona. Indiana. It is very difficult to anticipate what will trigger an individual’s intellectual curiosity but this book certainly gripped me. MATLAB® has a particular strength in data visualisation. using powerful language constructs. presumably since desktop computers were still a bit of a novelty back then. I would like to thank a number of people who assisted in the production of this book. of course. Euler. we didn’t cover applications in much depth at all. The authors of ‘Computational Physics’. I have been working through the exercises intermittently for my own interest and have documented my efforts in this book. quite specific piece of information. MATLAB® allows you to develop mathematical models quickly.S. still a work in progress. Coincidentally. Finally. who tolerated my absence when. Technology and Innovation via the Atlantis Programme. I cannot remember much attention being paid to the fact that this stuff was meant to be done on a computer.Preface I came across the book. Kevin Berwick West Lafayette. largely self imposed. Runge-Kutta and others were covered. and a particular thanks to Gareth O’ Donnell from the DIT for cultivating this link. And while all the usual methods. error reports and additions to the book are always welcome and can be sent to me at kevin. hospitality and many useful discussions while I was at Purdue. making it ideal for use for implementing the algorithms in this book. I would like to thank both of them sincerely for their interest. I would also like to thank the U. September 2012 Kevin Berwick Page 6 .

first entry in the vector N_uranium is N_uranium_initial time(1) = 0. % the initial condition. end % For comparison .1). %Discretize time into 100 intervals dt = 1e7.'r'.t.'b'). a vector of dimension npoints X 1.1.N_analytical. % Plot both numerical and analytical solution plot(time.(N_uranium(step)/tau)*dt.2 p2 dN/dt = -N/tau % Solve the Equation N_uranium_initial = 1000.4e9. calculate analytical solution t=0:1e8:10e9. %plots the numerical solution in red and the analytical solution in blue xlabel('Time in years') ylabel('Number of atoms') Kevin Berwick Page 7 . % this initializes the vector time to being all zeros N_uranium(1) = N_uranium_initial.to being all zeros time = zeros(npoints. N_analytical=N_uranium_initial*exp(-t/tau). % time step in years tau=4. %Initialise time for step=1:npoints-1 % loop over the timesteps and calculate the numerical solution N_uranium(step+1) = N_uranium(step) .1). %initial number of uranium atoms npoints = 100. % mean lifetime of 238 U N_uranium = zeros(npoints. based on 'Computational Physics' book by N Giordano and H Nakanishi Section 1.N_uranium. % initializes N_uranium. time(step+1) = time(step) + dt. Uranium Decay % % % % % 1D radioactive decay by Kevin Berwick.

It uses real data on Uranium and so the scales are slightly different than those used in the book.1000 900 800 700 Number of atoms 600 500 400 300 200 100 0 1 2 3 4 5 6 Time in years 7 8 9 10 x 10 9 Figure 1. Uranium decay as a function of time Note that the analytical and numerical solution are coincident in this diagram. Kevin Berwick Page 8 .

Simple Pendulum .1).1).5 -1 -1. a vector of dimension npoints X 1.1 clear. length= 1.to being all zeros time = zeros(npoints.5 0 1 2 3 4 5 6 time (seconds) 7 8 9 10 Figure 2. % this initializes the vector time to being all zeros theta(1)=0. theta(step+1) = theta(step)+omega(step)*dt time(step+1) = time(step) + dt. % you need to have some initial displacement. end plot(time. 1.(g/length)*theta(step)*dt. % time step in seconds omega = zeros(npoints.5 theta (radians) 0 -0.to being all zeros theta = zeros(npoints. %Discretize time into 250 intervals dt = 0.2.5 1 0. based on 'Computational Physics' book by N Giordano and H Nakanishi.'r' ). section 3. Note the oscillations grow with time. % initializes omega. % initializes theta.8 % acceleration due to gravity npoints = 250. otherwise the pendulum will not swing for step = 1:npoints-1 % loop over the timesteps omega(step+1) = omega(step) . a vector of dimension npoints X 1.Euler Method Kevin Berwick Page 9 . The Pendulum 3.3. !! % % % % % % Euler calculation of motion of simple pendulum by Kevin Berwick.theta.04. ylabel('theta (radians)').1 Solution using the Euler method Here is the code for the numerical solution of the equations of motion for a simple pendulum using the Euler method. %plots the numerical solution in red xlabel('time (seconds) '). %pendulum length in metres g=9.1).

%Discretize time into 250 intervals dt = 0.theta.2.1 -0. end.05 0 -0.(g/length)*theta(step)*dt.to being all zeros time = zeros(npoints.2 0.1 clear. ylabel('theta (radians)'). The code is below % % % % % % Euler_cromer calculation of motion of simple pendulum by Kevin Berwick.Cromer method Kevin Berwick Page 10 . % this initializes the vector time to being all zeros theta(1)=0.15 0. 0.04. theta(step+1) = theta(step)+omega(step+1)*dt.15 -0.1). a vector of dimension npoints X 1. % initializes omega. % time step in seconds omega = zeros(npoints. a vector of dimension npoints X 1.1).to being all zeros theta = zeros(npoints.25 0.1).'r' ).Cromer method. %pendulum length in metres g=9. % you need to have some initial displacement. section 3. Simple Pendulum: Euler . This problem with growing oscillations is addressed by performing the solution using the Euler .1. otherwise the pendulum will not swing for step = 1:npoints-1 % loop over the timesteps omega(step+1) = omega(step) .05 -0.1 theta (radians) 0. % initializes theta.8. %note that % this line is the only change between % this program and the standard Euler method time(step+1) = time(step) + dt. %plots the numerical solution in red xlabel('time (seconds) '). based on 'Computational Physics' book by N Giordano and H Nakanishi.2 -0. plot(time.25 0 1 2 3 4 5 6 time (seconds) 7 8 9 10 Figure 3. % acceleration due to gravity npoints = 250.1 Solution using the Euler-Cromer method. length= 1.3.

3.1.2 Simple Harmonic motion example using a variety of numerical approaches

In this example I use a variety of approaches in order to solve the following, very simple, equation of motion. It is based on Equation 3.9, with k and α =1.

I take 4 approaches to solving the equation, illustrating the use of the Euler, Euler Cromer, Second order Runge-Kutta and finally the built in MATLAB® solver ODE23. The solution using the built in MATLAB® solver ODE23 is somewhat less straightforward than those using the other techniques. A discussion of the technique follows. The first step is to take the second order ODE equation and split it into 2 first order ODE equations. These are Next you create a MATLAB® function that describes your system of differential equations. You get back a vector of times, T, and a matrix Y that has the values of each variable in your system of equations over the times in the time vector. Each column of Y is a different variable. MATLAB® has a very specific way to define a differential equation, as a function that takes one vector of variables in the differential equation, plus a time vector, as an argument and returns the derivative of that vector. The only way that MATLAB® keeps track of which variable is which inside the vector is the order you choose to use the variables in. You define your differential equations based on that ordering of variables in the vector, you define your initial conditions in the same order, and the columns of your answer are also in that order. In order to do this, you create a state vector y. Let element 1 be the vertical displacement, y1, and element 2 is the velocity,v. Next, we write down the state equations, dy1 and dy2. These are dy1=v; dy2=-y1 Next, we create a vector dy, with 2 elements, dy1 and dy2. Finally we call the MATLAB® ODE solver ODE23. We take the output of the function called my_shm. We perform the calculation for time values range from 0 to 100. The initial velocity is 0, the initial displacement is 10. The code to do this is here [t,y]=ode45(@my_shm,[0,100],[0,10]); Finally, we need to plot the second column of the y matrix, containing the displacement against time. The code to do this is

Kevin Berwick

Page 11

plot(t,y(:,2),'r'); Here is the top level code to do the comparison
% % Simple harmonic motion - comparison of Euler, Euler Cromer % and 2nd order Runge Kutta and built in MATLAB Runge Kutta % function ODE45to solve ODEs. % by Kevin Berwick, % based on 'Computational Physics' book by N Giordano and H Nakanishi, % section 3.1 % Equation is d2y/dt2 = -y % Calculate the numerical solution using Euler method in red [time,y] = SHM_Euler (10); subplot(2,2,1); plot(time,y,'r' ); axis([0 100 -100 100]); xlabel('Time'); ylabel('Displacement'); legend ('Euler method'); % Calculate the numerical solution using Euler Cromer method in blue [time,y] = SHM_Euler_Cromer (10); subplot(2,2,2); plot(time,y,'b' ); axis([0 100 -20 20]); xlabel('Time'); ylabel('Displacement'); legend ('Euler Cromer method'); % Calculate the numerical solution using Second order Runge-Kutta method in green [time,y] = SHM_Runge_Kutta (10); subplot(2,2,3); plot(time,y,'g' ); axis([0 100 -20 20]); xlabel('Time'); ylabel('Displacement'); legend ('Runge-Kutta method'); % Use the built in MATLAB ODE45 solver to solve the ODE % The function describing the SHM equations is called my_shm % The time values range from 0 to 100 % The initial velocity is 0, the initial displacement is 10 [t,y]=ode23(@SHM_ODE45_function,[0,100],[0,10]); % We need to plot the second column of the y matrix, containing the % displacement against time in black subplot(2,2,4); plot(t,y(:,2),'k'); axis([0 100 -20 20]); xlabel('Time'); ylabel('Displacement'); legend ('ODE45 Solver');

Kevin Berwick

Page 12

Here are the functions to do the individual calculations
% % Simple harmonic motion - Euler method % by Kevin Berwick, % based on 'Computational Physics' book by N Giordano and H Nakanishi, % section 3.1 % Equation is d2y/dt2 = -y function [time,y] = SHM_Euler (initial_displacement); npoints = 2500; dt = 0.04; %Discretize time into 250 intervals % time step in seconds

v = zeros(npoints,1); % initializes v, a vector of dimension npoints X 1,to being all zeros y = zeros(npoints,1); % initializes y, a vector of dimension npoints X 1,to being all zeros time = zeros(npoints,1); % this initializes the vector time to being all zeros y(1)=initial_displacement; % need some initial displacement % Euler solution for step = 1:npoints-1 % loop over the timesteps v(step+1) = v(step) - y(step)*dt; y(step+1) = y(step)+v(step)*dt; time(step+1) = time(step) + dt; end;

% % Simple harmonic motion - Euler Cromer method % by Kevin Berwick, % based on 'Computational Physics' book by N Giordano and H Nakanishi, % section 3.1 % Equation is d2y/dt2 = -y function [time,y] = SHM_Euler_Cromer (initial_displacement); npoints = 2500; dt = 0.04; %Discretize time into 250 intervals % time step in seconds

v = zeros(npoints,1); % initializes v, a vector of dimension npoints X 1,to being all zeros y = zeros(npoints,1); % initializes y, a vector of dimension npoints X 1,to being all zeros time = zeros(npoints,1); % this initializes the vector time to being all zeros y(1)=initial_displacement; % need some initial displacement % Euler Cromer solution for step = 1:npoints-1 % loop over the timesteps v(step+1) = v(step) - y(step)*dt; y(step+1) = y(step)+v(step+1)*dt; time(step+1) = time(step) + dt; end;

% % % % %

Simple harmonic motion - Second order Runge Kutta method by Kevin Berwick, based on 'Computational Physics' book by N Giordano and H Nakanishi, section 3.1

Kevin Berwick

Page 13

dy2=-y1. % this initializes the vector time to being all zeros y(1)=10.Built in MATLAB ODE45 method % by Kevin Berwick. a vector of dimension npoints X 1. % initializes y. % this initializes the vector time to being all zeros y(1)=initial_displacement. end.1). % y is the state vector y1 = y(1).to being all zeros time = zeros(npoints.y). a vector of dimension npoints X 1. a vector of dimension npoints X 1. % collect the equations into a column vector. %Discretize time into 250 intervals % time step in seconds v = zeros(npoints.to being all zeros y_dash = zeros(npoints.% Equation is d2y/dt2 = -y function [time.1).1 % Equation is d2y/dt2 = -y function dy = SHM_ODE45_function(t. velocity in column 1. % displacement in column 2 Kevin Berwick Page 14 .1). y_dash=y(step)+0. a vector of dimension npoints X 1.1).5*v(step)*dt.to being all zeros time = zeros(npoints.1). % section 3. v(step+1) = v(step)-y_dash*dt. % initializes v. % need some initial displacement for step = 1:npoints-1 % loop over the timesteps v_dash=v(step)-0. dt = 0.1). % initializes y.5*y(step)*dt.y] = SHM_Runge_Kutta(initial_displacement). a vector of dimension npoints X 1.to being all zeros y = zeros(npoints.04. % initializes y.1).to being all zeros y = zeros(npoints. % initializes v. % need some initial displacement v = zeros(npoints. % % Simple harmonic motion . % based on 'Computational Physics' book by N Giordano and H Nakanishi. % 2nd order Runge Kutta solution npoints = 2500. % initializes y. % y1 is displacement % y2 is velocity % write down the state equations dy1=v. v = y(2).1). a vector of dimension npoints X 1. y(step+1) = y(step)+v_dash*dt.to being all zeros v_dash = zeros(npoints. time(step+1) = time(step)+dt.

dy = [dy1. Runge Kutta and Matlab ODE45 solver. Simple pendulum solution using Euler.dy2]. Euler Cromer. 100 Euler method 20 Euler Cromer method Displacement 0 -50 -100 Displacement 0 50 Time 100 50 10 0 -10 -20 0 50 Time 100 20 Runge-Kutta method 20 ODE45 Solver Displacement 0 -10 -20 Displacement 0 50 Time 100 10 10 0 -10 -20 0 50 Time 100 Figure 4. Kevin Berwick Page 15 .

This solution uses q=1 % % % % % % Euler_cromer calculation of motion of simple pendulum with damping by Kevin Berwick. % initializes theta.to being all zeros theta = zeros(npoints.to being all zeros time = zeros(npoints. end. %plots the numerical solution in red xlabel('time (seconds) '). % In the Euler method. section 3. % initializes omega. plot(time. length= 1. not swing % you need to have some initial displacement.3. the previous value of omega % and the previous value of theta are used to calculate the new values of omega and theta. g=9. q=1.04. a vector of dimension npoints X 1. % In the Euler Cromer method.2. otherwise the pendulum will for step = 1:npoints-1 % loop over the timesteps omega(step+1) = omega(step) . dt = 0.theta. % this initializes the vector time to being all zeros theta(1)=0.2 Solution for a damped pendulum using the Euler-Cromer method. theta(step+1) = theta(step)+omega(step+1)*dt. a vector of dimension npoints X 1. However. the previous value of omega % and the previous value of theta are used to calculate the the new value % of omega. Kevin Berwick Page 16 .8.1). based on 'Computational Physics' book by N Giordano and H Nakanishi. ylabel('theta (radians)'). .1). %pendulum length in metres % acceleration due to gravity % damping strength %Discretize time into 250 intervals % time step in seconds omega = zeros(npoints. npoints = 250.'r' ).(g/length)*theta(step)*dt-q*omega(step)*dt. the NEW value of omega is used to calculate the new % theta % time(step+1) = time(step) + dt.1).2 clear.

1 theta (radians) 0.2 0. The damped pendulum using the Euler-Cromer method Kevin Berwick Page 17 .1 -0.15 0.05 -0.0.05 0 -0.15 0 1 2 3 4 5 6 time (seconds) 7 8 9 10 Figure 5.

04. a vector of dimension npoints X 1. % So. temporary_theta_step_plus_1 = theta(step)+omega(step+1)*dt. % acceleration due to gravity q=0.3 % clear. % section 3. a vector of dimension npoints X 1. not swing omega(1)=0. % For plotting purposes it is nice to keep (-pi<theta<pi). % We need to adjust theta after each iteration so as to keep it between +/-pi % The pendulum can now swing right around the pivot.2.to being all zeros theta = zeros(npoints. % initializes omega. % Euler Cromer Solution for non-linear. % damping strength Omega_D=2/3. end.5. All of the next five plots were produced using the code below with slight modifications in either the input parameters or the plots.1). % you need to have some initial displacement. add 2*pi.2. driven pendulum :. % loop over the timesteps % Note error in book in Equation for Example 3. the previous value of omega % and the previous value of theta are used to calculate the new values of omega and theta. elseif (temporary_theta_step_plus_1 > pi) temporary_theta_step_plus_1= temporary_theta_step_plus_1-2*pi.If theta is > pi. subtract 2*pi % If the lines below between the ****** are commented out you get 3. . % this initializes the vector time to being all zeros theta(1)=0.the Physical pendulum. damped. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% % In the Euler method. % Theta is an angular variable so values of theta that differ by 2*pi correspond to the same position.1). %******************************************************************************************** % Update theta array theta(step+1)=temporary_theta_step_plus_1.1). % based on 'Computational Physics' book by N Giordano and H Nakanishi. if theta is <-pi. length= 9. for step = 1:npoints-1. % time step in seconds omega = zeros(npoints. otherwise the pendulum will Kevin Berwick Page 18 .3.3 omega(step+1)=omega(step)+(-(g/length)*sin(theta(step))q*omega(step)+F_Drive*sin(Omega_D*time(step)))*dt. npoints =15000.8. %Discretize time dt = 0. %pendulum length in metres g=9.to being all zeros time = zeros(npoints. damped. corresponding to theta>2*pi.8. driven pendulum % by Kevin Berwick. F_Drive=1.6 (b)% bottom %******************************************************************************************** if (temporary_theta_step_plus_1 < -pi) temporary_theta_step_plus_1= temporary_theta_step_plus_1+2*pi.3 Solution for a non-linear. using the Euler-Cromer method. % initializes theta.

8 0.8 -1 0 10 20 30 time (seconds) 40 50 60 Figure 6. using the Euler-Cromer method.6 0. 1 0.4 theta (radians) 0.4 -0. F_drive =0. plot (theta. Results from Physical pendulum. ylabel('omega (seconds)'). end.'r' ).% In the Euler Cromer method.2 0 -0.omega. the previous value of omega % and the previous value of theta are used to calculate the the new value % of omega. However. the NEW value of omega is used to calculate the new % theta % time(step+1) = time(step) + dt. %plots the numerical solution xlabel('theta (radians)').2 -0.6 -0.5 Kevin Berwick Page 19 .

2 Kevin Berwick Page 20 . F_drive =1.4 3 2 1 0 -1 -2 -3 -4 theta (radians) 0 10 20 30 time (seconds) 40 50 60 Figure 7.Results from Physical pendulum. using the Euler-Cromer method.

4 -0. Results from Physical pendulum.2 0 0.5 -4 -3 -2 -1 0 1 theta (radians) 2 3 4 Figure 9. F_Drive=1. using the Euler-Cromer method.2 -0.6 -0. Results from Physical pendulum.4 -0.0.6 0.5 -2 -2.8 -0.5 -1 -1.8 0.4 0.4 omega (radians/second) 0. using the Euler-Cromer method.2 theta (radians) 0.5 omega (radians/second) 1 0.6 0.2 Kevin Berwick Page 21 .2 0 -0.8 1 Figure 8.5 2 1.5 2.8 -1 -0.5 0 -0. F_drive =0.6 -0.

%pendulum length in metres g=9. Note that this figure was produced using npoints = 15000. 2.5 omega (radians/second) 1 0.2.to being all zeros theta = zeros(npoints. Increase resolution with npoints=15000. length= 9. npoints =1500000. % this initializes the vector time to being all zeros theta(1)=0. % section 3.8. using the Euler-Cromer method.9.5 2 1.2.3 %I modified the code in order to produce the Poincare section shown in Fig 3.Results from Physical pendulum.5 0 -0.2 % Euler Cromer Solution for non-linear.2. % based on 'Computational Physics' book by N Giordano and H Nakanishi.5 -1 -1. a vector of dimension npoints X 1. % It uses a little MATLAB trick in order to prevent plotting of any points that were not in % phase with the driving force. for step = 1:npoints-1. Kevin Berwick Page 22 . % you need to have some initial displacement.5 -2 -2.1).1).If you want higher resolution. % damping strength Omega_D=2/3.1).5 -4 -3 -2 -1 0 1 theta (radians) 2 3 4 Figure 10. F_Drive =1. simply increase the resolution by changing npoints. driven pendulum % by Kevin Berwick. % acceleration due to gravity q=0. a vector of dimension npoints X 1.8. damped. % initializes theta.5.to being all zeros time = zeros(npoints. clear. otherwise the pendulum will not swing omega(1)=0. F_Drive=1. % initializes omega. %Discretize time dt = 0. F_Drive=1.04. % time step in seconds omega = zeros(npoints.

scatter (theta. %plots the numerical solution xlabel('theta (radians)'). end. if (temporary_theta_step_plus_1 < -pi) temporary_theta_step_plus_1= temporary_theta_step_plus_1+2*pi. 1 0.omega.5 omega (radians/second) 0 -0.3 omega(step+1)=omega(step)+(-(g/length)*sin(theta(step))q*omega(step)+F_Drive*sin(Omega_D*time(step)))*dt. elseif (temporary_theta_step_plus_1 > pi) temporary_theta_step_plus_1= temporary_theta_step_plus_1-2*pi.'k' ).omega. time(step+1) = time(step) + dt.2 ). ylabel('omega (radians/second)').5 -2 -4 -3 -2 -1 0 1 theta (radians) 2 3 4 Figure 11. temporary_theta_step_plus_1 = theta(step)+omega(step+1)*dt. end. % Only plot omega and theta point when omega is in phase with the driving force Omega_D I=find(abs(rem(time.02).5 -1 -1. Poincare section (Strange attractor) Omega as a function of theta. % Update theta array theta(step+1)=temporary_theta_step_plus_1. %plots the numerical solution plot (theta. 2*pi/Omega_D)) > 0. omega(I)=NaN.% loop over the timesteps % Note error in book in Equation for Example 3.2 Kevin Berwick Page 23 . theta(I)=NaN. F_Drive =1.

time(Z)=NaN.'k').04. based on 'Computational Physics' book by N Giordano and H Nakanishi. Omega_D).35 1. %Further filter the results so that only results in phase with the driving force % F_Drive are displayed. g=9. q=0. section 3. a vector of dimension npoints X 1. and calculate the bifurcation diagram.3.1).1:13. time(I)=NaN. ylabel('theta (radians)'). Omega_D=2/3.4. % Calculate the plot of theta as a function of time for the current drive step % using the function :. note % that the period is 3*pi.8. I=find (time< 3*pi*300).3 function [time. F_Drive=1.5 1 3]). dt = 0. % Remove all NaN values from the array to reduce dataset size time(isnan(time)) = []. You need to have the function 'pendulum_function' available in order to run this. theta(isnan(theta)) = []. % initializes theta. % % % % Euler_cromer calculation of motion of physical pendulum by Kevin Berwick. theta(Z)=NaN.to being all zeros theta = zeros(npoints. hold on. 2*pi/Omega_D)) > 0.8. based on 'Computational Physics' book by N Giordano and H Nakanishi. section 3. length= 9.Omega_D).theta] = pendulum_function(F_Drive. end. axis([1.to being all zeros Kevin Berwick Page 24 .5. a vector of dimension npoints X 1.01).theta.theta]= pendulum_function(F_Drive. %pendulum length in metres % acceleration due to gravity % damping strength %Discretize time % time step in seconds omega = zeros(npoints. % initializes omega.35+F_Drive_step/100. % Replace all those values NOT in phase with NaN Z=find(abs(rem(time.pendulum_function [time. theta(I)=NaN. xlabel('F Drive'). npoints =100000.1).4 Bifurcation diagram for the pendulum % % % % % Program to perform Euler_cromer calculation of motion of physical pendulum by Kevin Berwick. %Filter the results to exclude initial transient of 300 periods. % Now plot the results plot(F_Drive. for F_Drive_step=1:0.

not swing omega(1)=0.4 theta (radians) 2.1). end. % this initializes the vector time to being all zeros theta(1)=0. otherwise the pendulum will for step = 1:npoints-1. elseif (temporary_theta_step_plus_1 > pi) temporary_theta_step_plus_1= temporary_theta_step_plus_1-2*pi.4 F Drive 1.2.2 2 1.time = zeros(npoints.4 1.8 1. end. temporary_theta_step_plus_1 = theta(step)+omega(step+1)*dt. Bifurcation diagram for the pendulum Kevin Berwick Page 25 .35 1.6 2. % Increment time time(step+1) = time(step) + dt.45 1.8 2. % Make corrections to keep theta between pi and -pi if (temporary_theta_step_plus_1 < -pi) temporary_theta_step_plus_1= temporary_theta_step_plus_1+2*pi. 3 2.6 1.2 1 1. % Update theta array theta(step+1)=temporary_theta_step_plus_1. % you need to have some initial displacement. % loop over the timesteps omega(step+1)=omega(step)+(-(g/length)*sin(theta(step))q*omega(step)+F_Drive*sin(Omega_D*time(step)))*dt.5 Figure 12.

to being all zeros y = zeros(npoints. % initializes y.to being all zeros z = zeros(npoints. npoints =500000.1). r=25.1). y(step+1)=y(step)+(-x(step)*z(step)+r*x(step)-y(step))*dt. a vector of dimension npoints X 1. for step = 1:npoints-1 % loop over the timesteps and solve the difference equations x(step+1)=x(step)+sigma*(y(step)-x(step))*dt. a vector of dimension npoints X 1.3. % based on 'Computational Physics' book by N Giordano and H Nakanishi. subplot (2. Kevin Berwick Page 26 . a vector of dimension npoints X 1. % Update time array time(step+1) = time(step) + dt. % initializes x.1. sigma=10. % initializes z.6 The Lorenz Model The equations are the same as those as in 3.1). % section 3. end.29 ( ) The equations I used in the numerical solution are ( ( ( ) ) ) % % Euler calculation of Lorenz equations % by Kevin Berwick.to being all zeros time = zeros(npoints. % this initializes the vector time to being all zeros x(1)=1.1).0001.6 % clear a=10.1). % time step in seconds x = zeros(npoints. z(step+1)=z(step)+(x(step)*y(step)-b*z(step))*dt. %Discretize time dt = 0. b=8/3.

ylabel('z') 60 40 z 20 0 0 5 10 15 20 25 time 30 35 40 45 50 60 40 z 20 0 -20 -15 -10 -5 0 x 5 10 15 20 Figure 13.1.'g' ).2). xlabel('time').'b' ). ylabel('z').z.z. xlabel('x'). Variation of z as a function of time and corresponding strange attractor Kevin Berwick Page 27 . plot (x. subplot (2.plot(time.

4. by Kevin Berwick. y=0. hold on. axis([-1 1 -1 1]). % time step in years % initialise position of planet in AU % initialise velocity of planet in AU/yr % Plot the Sun at the origin plot(0.'-k').update positions using newly calculated velocities x_new=x+v_x_new*dt. xlabel('x(AU)'). for step = 1:npoints-1. % loop over the timesteps radius=sqrt(x^2+y^2).0. 'MarkerFaceColor'. v_y=v_y_new.(4*pi^2*x*dt)/(radius^3). % Compute new velocities in the x and y directions v_x_new=v_x .1 npoints=500.'MarkerSize'.'yellow'). v_y=2*pi. x=1. % Update x and y velocities with new velocities v_x=v_x_new. y_new=y+v_y_new*dt. Kevin Berwick Page 28 . % Update x and y with new positions x=x_new. % Euler Cromer Step . v_x=0. % Plot planet position immediately plot(x_new. dt = 0. The Solar System 4. y=y_new. end.30.'oy'.1 Kepler’s Laws % % % % % % Planetary orbit using Euler Cromer methods.y_new. drawnow. v_y_new=v_y .(4*pi^2*y*dt)/(radius^3).002. ylabel('y(AU)'). based on 'Computational Physics' book by N Giordano and H Nakanishi Section 4.

% loop over the timesteps radius=sqrt(x^2+y^2). x=1.5*(4*pi^2*y*dt)/(radius^3). % update positions and new y velocity Kevin Berwick Page 29 . % initialise x velocity of planet in AU/yr v_y=2*pi.6 0.6 -0.'yellow').4 -0. axis([-1 1 -1 1]). % time step in years t=0. ylabel('y(AU)').2 0 x(AU) 0.6 0.8 1 Figure 14. hold on. xlabel('x(AU)').6 -0.2 y(AU) 0 -0. dt = 0.2 0. % % % Planetary orbit using second order Runge-Kutta method.'MarkerSize'. % by Kevin Berwick. 'MarkerFaceColor'.1 % % npoints=500.8 -1 -1 -0.1 0.5*v_y*dt.0.002.4 0. % initialise position of planet in AU y=0. v_y_dash=v_y . for step = 1:npoints-1. v_x=0.'oy'.30.4 -0. % Compute Runge Kutta values for the y equations y_dash=y+0.8 0. Simulation of Earth orbit around the Sun Here is the code using a second order Runge Kutta method giving the same results.2 -0. % initialise y velocity of planet in AU/yr % Plot the Sun at the origin plot(0.4 0.8 -0. % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 4.0.

Clearly the orbit is unstable. v_y_new=v_y-(4*pi^2*y_dash*dt)/(radius^3).05 and got the Figure below.y_new.1 we are asked to change the time step to show that for dt > 0.y_new=y+v_y_dash*dt. drawnow.1. This is in accordance with the rule of thumb that the time step should be less than 1% of the characteristic time scale of the problem. % Update x and y velocities with new velocities v_x=v_x_new.5*(4*pi^2*x*dt)/(radius^3). % Plot planet position immediately plot(x_new. % update positions using newly calculated velocity x_new=x+v_x_dash*dt.'-k').5*v_x*dt.01 years.1 Ex 4.0. % Update x and y with new positions x=x_new. y=y_new. 4. Kevin Berwick Page 30 . v_x_dash=v_x . you get an unsatisfactory result. v_y=v_y_new. end. % Compute Runge Kutta values for the x equations x_dash=x+0. v_x_new=v_x-(4*pi^2*x_dash*dt)/(radius^3).1 Planetary motion results using different time steps In Exercise 4. I chose dt=0.

05 I also looked at changing the velocity to look at the effect of increasing the value of the initial velocity.5 1 1.2 1.5 1 0. below.5 0 x(AU) 0. Simulation of Earth orbit with time step of 0.5 y(AU) 0 -0.5 -1 -1. while returning the time step to 0. Kevin Berwick Page 31 .5 -1 -0.5 -2 -2 -1.002.5 2 Figure 15. Here is the plot.

002. dt is 0. but dt is increased to 0.4 -0.002.2 0 y(AU) -0. 0.8 -0.4 0.2 0 0.2 x(AU) 0.8 1 Figure 16. Clearly.6 -0. Kevin Berwick Page 32 .6 0. time step is 0.4 0.4 -0. initial y velocity of 4.05.2 -0.with an initial y velocity of 4. Here is the plot with the same initial y velocity of 4.6 0. Simulation of Earth orbit. the instability is apparent.

002.05 Here is the result for an initial y velocity of 8. 2500 points and Runge Kutta method Here is the code and Plot for an initial y velocity of 8. 2.5 -2. npoints=2500.5 -1 -0.5 0 x(AU) 0. Simulation of Earth orbit.5 y(AU) 0 -0. The Runge Kutta Method is used here.5 -1 -1.5 -2 -2. initial y velocity of 4. npoints=2500. Note the relative stability of the orbit.5 1 0.Simulation of Earth orbit.5 -2 -2. time step is 0.5 Figure 17.2. Kevin Berwick Page 33 . time step is 0. dt is 0.5 2 1.5 1 1.5 y(AU) 0 -0.5 2 1.5 -1 -1..5 1 0.5 2 2.05. initial y velocity of 8.5 -5 -4 -3 -2 x(AU) -1 0 1 2 Figure 18. The Runge Kutta Method is used here. dt is 0.002.5 -2 -1.

v_y=8. % update positions and new y velocity y_new=y+v_y_dash*dt. x=1. % Compute Runge Kutta values for the x equations x_dash=x+0. % axis([-1 1 -1 1]). Kevin Berwick Page 34 . v_y_dash=v_y .5*v_x*dt. v_y=v_y_new. for step = 1:npoints-1. % update positions using newly calculated velocity x_new=x+v_x_dash*dt.5*(4*pi^2*x*dt)/(radius^3). v_x_dash=v_x .% % % Planetary orbit using second order Runge-Kutta method. ylabel('y(AU)'). dt = 0.1 % % % npoints=500. v_x_new=v_x-(4*pi^2*x_dash*dt)/(radius^3).'oy'. y=y_new. % initialise position of planet in AU % initialise x velocity of planet in AU/yr % initialise y velocity of planet in AU/yr % initialise y velocity of planet in AU/yr % Plot the Sun at the origin plot(0. % Compute Runge Kutta values for the y equations y_dash=y+0.0.'-k'). % Update x and y with new positions x=x_new. v_y_new=v_y-(4*pi^2*y_dash*dt)/(radius^3). drawnow. % time step in years t=0.5*(4*pi^2*y*dt)/(radius^3). % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 4. npoints=2500.0. end. v_x=0. remove in order to see effect of changing time step xlabel('x(AU)'). y=0. % v_y=2*pi. hold on. % Plot planet position immediately plot(x_new.30.'yellow').5*v_y*dt. % loop over the timesteps radius=sqrt(x^2+y^2).0. 'MarkerFaceColor'.05.'MarkerSize'. % by Kevin Berwick. % Update x and y velocities with new velocities v_x=v_x_new.y_new.

The Runge Kutta Method is used here 4. The time step is 0.2.2 npoints=1000. % time step in years t=0. % initialise y velocity of planet in AU/yr v_y=5. dt is 0. x=1. % initialise x velocity of planet in AU/yr % v_y=2*pi.Plot for an initial y velocity of 8.5 1 0. by Kevin Berwick.5 2 1.2 Orbits using different force laws Here is the code to calculate the elliptical orbit for a force law with β=2.5 y(AU) 0 -0. dt = 0.5 -3 -2 -1 0 x(AU) 1 2 3 Figure 19. % initialise position of planet in AU y=0. npoints=2500.001 years. % initialise y velocity of planet in AU/yr % Plot the Sun at the origin Kevin Berwick Page 35 .5 -2 -2. % % % % % % % % Planetary orbit using second order Runge-Kutta method. v_x=0. based on 'Computational Physics' book by N Giordano and H Nakanishi Section 4.05.001.5 -1 -1.

% Update x and y velocities with new velocities v_x=v_x_new.plot(0. hold on. v_y_new=v_y-(4*pi^2*y_dash*dt)/(radius^3).5*v_y*dt.0. v_y=v_y_new.5*(4*pi^2*y*dt)/(radius^3). % Compute Runge Kutta values for the y equations y_dash=y+0. v_x_dash=v_x .y_new. % Compute Runge Kutta values for the x equations x_dash=x+0. v_x_new=v_x-(4*pi^2*x_dash*dt)/(radius^3). v_y_dash=v_y .5*v_x*dt. % Plot planet position immediately plot(x_new. % update positions using newly calculated velocity x_new=x+v_x_dash*dt.5*(4*pi^2*x*dt)/(radius^3). xlabel('x(AU)'). % loop over the timesteps radius=sqrt(x^2+y^2).'yellow'). title('Beta = 2') axis([-1 1 -1 1]). % Update x and y with new positions x=x_new. ylabel('y(AU)').30. % update positions and new y velocity y_new=y+v_y_dash*dt. drawnow.0.'MarkerSize'. end.0. for step = 1:npoints-1.'-k').'oy'. 'MarkerFaceColor'. Kevin Berwick Page 36 . y=y_new.

% initialise x velocity of planet in AU/yr % v_y=2*pi. ylabel('y(AU)'). Here is the code to calculate the elliptical orbit for a force law with β=2. x=1. for step = 1:npoints-1. % initialise y velocity of planet in AU/yr % Plot the Sun at the origin plot(0. title('Beta = 2.2 -0.4 0.001 years.0. v_x=0. based on 'Computational Physics' book by N Giordano and H Nakanishi Section 4.4 -0.6 -0.6 0.4 -0. xlabel('x(AU)'). by Kevin Berwick.'oy'.4 0.30. % time step in years t=0.6 0.2 0 x(AU) 0.Beta = 2 1 0. Kevin Berwick Page 37 . The time step is 0.8 0. % % % % % % Planetary orbit using second order Runge-Kutta method.6 -0.8 -0.2 y(AU) 0 -0.'yellow').'MarkerSize'. % initialise y velocity of planet in AU/yr v_y=5.2 npoints=1000.8 1 Figure 20. 'MarkerFaceColor'.8 -1 -1 -0.5.001. Orbit for a force law with β=2.2 0. hold on. % initialise position of planet in AU y=0. The time step is 0.5') axis([-1 1 -1 1]).001 years. dt = 0.

% loop over the timesteps radius=sqrt(x^2+y^2).5*(4*pi^2*y*dt)/(radius^3. Kevin Berwick Page 38 .5*v_x*dt.5).5*(4*pi^2*x*dt)/(radius^3. % Update x and y with new positions x=x_new. v_y_new=v_y-(4*pi^2*y_dash*dt)/(radius^3. % update positions and new y velocity y_new=y+v_y_dash*dt. % Compute Runge Kutta values for the x equations x_dash=x+0. v_x_new=v_x-(4*pi^2*x_dash*dt)/(radius^3. y=y_new.5). v_x_dash=v_x . % Update x and y velocities with new velocities v_x=v_x_new. drawnow.0. % update positions using newly calculated velocity x_new=x+v_x_dash*dt. v_y=v_y_new.5). % Plot planet position immediately plot(x_new.5*v_y*dt.y_new.5).'-k').0. end. % Compute Runge Kutta values for the y equations y_dash=y+0. v_y_dash=v_y .

4 0.5 1 0.6 0. Here is the Figure for β=3.2 -0.8 0.6 -0.8 -0.001 years.6 -0.2 y(AU) 0 -0.2 0.6 0.4 -0.4 -0.Beta = 2.2 0 x(AU) 0.4 0. The time step is 0. Check out the planet being ejected from the solar system!! The Sun is at the origin Kevin Berwick Page 39 . Orbit for a force law with β=2.8 1 Figure 21.8 -1 -1 -0.5.

( ) ( ( ( ( ) ) ) ) Now. first order. Orbit for a force law with β=3. Let’s do the Maths here. differential equations. Kevin Berwick Page 40 . write each 2nd order differential equations as two. 4.3 Precession of the perihelion of Mercury.Beta =3 10 8 6 4 2 y(AU) 0 -2 -4 -6 -8 -10 -10 -8 -6 -4 -2 0 x(AU) 2 4 6 8 10 Figure 22.

( ) ( ) So. but what about if we chose to attack the problem using the Runge Kutta method. the difference equation set using the Euler Cromer method is ( ) ( ) We could go ahead and code this. The relevant equations are ( ) ( ) ( ) ( ) Kevin Berwick Page 41 .

here is the code for an alpha value of 0. we simply use the Euler method but using y’ and v’ in the equations. y’ and v’ is evaluated by the Euler method at .In the case of the y equations for example.0008 Kevin Berwick Page 42 . Then to get the new values of y and v. So.

v_y_dash=v_y . % Calculate radius relativity_factor=1+alpha/radius^2. I need to monitor the time derivative of the radius and identify when it % changes from positive to negative.0. % Update positions using newly calculated velocity x_new=x+v_x_dash*dt. % initialise y velocity of planet in AU/yr alpha=0. Then calculate the angle made % by the vector joining the origin and this point with the x axis.0008.% % % % % % % % Precession of mercury using second order Runge-Kutta method. for step = 1:npoints-1.5*v_x*dt. % Compute Runge Kutta values for the x equations x_dash=x+0. % initialise x velocity of planet in AU/yr v_y=8. a vector of dimension npoints X 1.1).5*(4*pi^2*y*dt)*relativity_factor/(radius^3). % time step in years time = zeros(npoints. based on 'Computational Physics' book by N Giordano and H Nakanishi Section 4.5*v_y*dt. time_derivative=(new_radius-radius)/dt.0001.5*(4*pi^2*x*dt)*relativity_factor/(radius^3).0.3 npoints=30000. % Update x and y velocities with new velocities v_x=v_x_new. by Kevin Berwick. v_x_new=v_x-(4*pi^2*x_dash*dt)*relativity_factor/(radius^3). dt = 0. % initialise x position of planet in AU y=0.47. % loop over the timesteps % Increment total elapsed time time(step+1) = time(step) + dt. radius=sqrt(x^2+y^2). v_x_dash=v_x . % initializes angleInDegrees. new_radius=sqrt(x_new^2+y_new^2).1).to being all zeros x=0. % Update positions and new y velocity y_new=y+v_y_dash*dt. Kevin Berwick Page 43 . % Compute Runge Kutta values for the y equations y_dash=y+0.to being all zeros angleInDegrees = zeros(npoints. v_y_new=v_y-(4*pi^2*y_dash*dt)*relativity_factor/(radius^3). % Identify semi-major axes in the planetary orbit and draw them on the % plot. a vector of dimension npoints X 1. % initialise x position of planet in AU v_x=0. % initializes time. v_y=v_y_new.2.

the value % This is a way of identifying the long axis of the orbit. or slope. % returning the coefficient. xlabel('time(year)'). 0 to 2. ' and slope = '.% Update x and y with new positions x=x_new. scatter (time. % Remove all NaN values from the array to reduce dataset size time(isnan(time)) = []. if this is not the case.01). if abs(time_derivative) <0. Remove data with angles = zero or % less. Polynomial_values = polyval(poly_matrix. angleInDegrees(I)=NaN. angleInDegrees(isnan(angleInDegrees)) = []. Note that % angle_In_Degrees will remain zero [theta.1:3]. axis([0 3 0 20]). this means we only plot the angles of the long axes of the orbit I=find(angleInDegrees < 0. slope=poly_matrix(1). % Perform a linear fit to the data.Polynomial_values. end. degree N=1. y=y_new. 'or'). % convert to degrees end.2). ylabel('theta(degrees)'). 'LineWidth'.1) .angleInDegrees. % Evaluate the polynomial at times from Kevin Berwick Page 44 . % Plot the fit time_for_fit=[0:0. to the variable slope poly_matrix = polyfit(time.num2str(alpha).0025.5 plot(time_for_fit. % Plot Orbit orientation versus time. angleInDegrees. 'g'. %Convert Cartesian coordinates to polar. title(['Orbit orientation versus time for alpha='.time_for_fit). noting that the result is in radians angleInDegrees(step)= 180*(theta/pi). num2str(slope)]).rho] = cart2pol(x_new. hold on. time(I)=NaN.y_new).

The slope is just the time derivative of theta.003 0.4 10.Orbit orientation versus time for alpha=0.7 21. We note the value of the slope each time. Kevin Berwick Page 45 .0005 0.002 0.0008 and slope = 8. All we do is change one line in the code above.9 33.5 1 1. Orbit orientation as a function of time If we rerun the code for various values of alpha.0007 0.9 We can use this next script to plot this data and then do a fit to finally calculate the precession rate of Mercury. circled red.5 time(year) 2 2.5115 20 18 16 14 theta(degrees) 12 10 8 6 4 2 0 0 0.001 0.5 3 Figure 23. alpha 0.3 7. We get the following values.6 45.004 Time derivative of theta (precession rate) 5.

% Evaluate the polynomial at points in the vector plot(alpha_for_fit.' AU^2 is '. Mercury_rate = poly_matrix(1)*alpha_relativity.0005 0. 'ko') % Perform a linear fit to the data. precession_rate=[5.1f'). % predicted alpha value from General Relativity % Load up data alpha=[0. . ylabel('Precession rate (degrees/year)'). % Perform the fit % Plot the fit on the data alpha_for_fit=[0:0. or slope. precession_rate. precession_rate. hold on. Answer is in degrees per year Mercury_rate_arc_sec_century = Mercury_rate*100 *3600. xlabel('alpha'). Finally.9 33.3 7. Polynomial_values = polyval(poly_matrix.004]. % returning the coefficient. 'g'.001 0.' arc/s per century']). % Convert to arc/s per century title(['Calculated precession rate of Mercury for alpha = '. 'LineWidth'.002 0. % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 4.4 10. here are the results Kevin Berwick Page 46 . % Plot graph scatter(alpha.004 0 40]).3 % % alpha_relativity=1.7 21.alpha_for_fit).004]. degree N=1.num2str(Mercury_rate_arc_sec_century.% % % Precession of mercury using second order Runge-Kutta method. % Format graph axis([0 0.6 45.003 0. Note you can't use the MATLAB function polyval as the % intercept value of the fitted line would dominate the precession rate.0001:0.2).0007 0.1e-8. num2str(alpha_relativity).'%. % Data plotting and fitting routines % by Kevin Berwick. 1). % Extract the slope from the fit and multiply it by the predicted alpha % value from General Relativity.Polynomial_values. % poly_matrix = polyfit(alpha.9].

5 2 alpha 2.8 arc/s per century 40 35 30 25 20 15 10 5 0 Precession rate (degrees/year) 0 0.Calculated precession rate of Mercury for alpha = 1. Calculated precession rate of Mercury Kevin Berwick Page 47 .5 3 3.5 x 10 4 -3 Figure 24.1e-008 AU2 is 45.5 1 1.

9e27.2.0001. M_j=1. v_e_x(1)=v_e_x_initial. r_j=zeros(npoints. y_j=zeros(npoints.1). y_e=zeros(npoints. y_e_initial=0. Do not be tempted to start taking absolute values of the subtracted positions in a naïve bid to ‘correct’ the equations. the direction of the various forces between the 3 bodies is elegantly captured in the pseudocode given in Ex 4. Earth and Sun. x_e_initial=1. Here is the code % % % % % % % 3 body simulation of Jupiter.75 AU/year % Create arrays to store position and velocity of Earth x_e=zeros(npoints. v_j_y=zeros(npoints. x_j_initial=5. % Initialise positions and velocities of Earth and Jupiter x_e(1)=x_e_initial.2 AU/11. v_e_x_initial=0.7549. dt = 0. r_e_j=zeros(npoints. v_e_y_initial=2*pi.1). Use Euler Cromer method based on 'Computational Physics' book by N Giordano and H Nakanishi Section 4. M_e=6e24. % Create arrays to store position and velocity of Jupiter x_j=zeros(npoints. assume at opposition initially % Initial velocity of Jupiter in AU/yr % This is 2*pi*5.2.1).4 by Kevin Berwick npoints=1000000. r_e=zeros(npoints.1). y_e(1)=y_e_initial. v_j_x=zeros(npoints. % time step in years. y_j_initial=0. v_j_y_initial= 2. % Mass of the Sun in kg % Mass of the Earth in kg % Mass of Jupiter in kg % Initial position of Earth in AU % Initial velocity of Earth in AU/yr % Initial position of Jupiter in AU.1). M_s=2e30.1).1).1). v_e_x=zeros(npoints.1). v_j_x_initial=0. Kevin Berwick Page 48 . Firstly. v_e_y(1)=v_e_y_initial.85 years = 2.4 The three body problem and the effect of Jupiter on Earth A couple of points on this problem.1).4.1). v_e_y=zeros(npoints.

'k'). % Compute x and y components for new velocity of Jupiter v_j_x(i+1)=v_j_x(i)-4*pi^2*x_j(i)*dt/r_j(i)^3-4*pi^2*(M_j/M_s)*(x_j(i)x_e(i))*dt/r_e_j(i)^3. xlabel('x(AU)'). y_j(i+1)=y_j(i)+v_j_y(i+1)*dt. 'r'. % Compute x and y components for new velocity of Earth v_e_x(i+1)=v_e_x(i)-4*pi^2*x_e(i)*dt/r_e(i)^3-4*pi^2*(M_j/M_s)*(x_e(i)x_j(i))*dt/r_e_j(i)^3. Kevin Berwick Page 49 . y_j(1)=y_j_initial. v_e_y(i+1)=v_e_y(i)-4*pi^2*y_e(i)*dt/r_e(i)^3-4*pi^2*(M_j/M_s)*(y_e(i)y_j(i))*dt/r_e_j(i)^3. % loop over the timesteps % Calculate distances to Earth from Sun. Note the use of the NEW vlaue of velocity in both equations x_e(i+1)=x_e(i)+v_e_x(i+1)*dt. Jupiter from Sun and Jupiter % to Earth for current value of i r_e(i)=sqrt(x_e(i)^2+y_e(i)^2). v_j_x(1)=v_j_x_initial. v_j_y(i+1)=v_j_y(i)-4*pi^2*y_j(i)*dt/r_j(i)^3-4*pi^2*(M_j/M_s)*(y_j(i)y_e(i))*dt/r_e_j(i)^3. x_j(i+1)=x_j(i)+v_j_x(i+1)*dt. plot(x_e.y_j. v_j_y(1)=v_j_y_initial. title('3 body simulation . r_e_j(i)=sqrt((x_e(i)-x_j(i))^2 +(y_e(i)-y_j(i))^2). ylabel('y(AU)').Jupiter Earth').x_j(1)=x_j_initial. r_j(i)=sqrt(x_j(i)^2+y_j(i)^2). axis([-7 7 -7 7]). y_e(i+1)=y_e(i)+v_e_y(i+1)*dt.y_e. % % Use Euler Cromer technique to calculate the new positions of Earth and % Jupiter. x_j. for i = 1:npoints-1. end.

Here are the results using the actual mass of Jupiter 3 body simulation . Kevin Berwick Page 50 .Jupiter Earth 6 4 2 y(AU) 0 -2 -4 -6 -6 -4 -2 0 x(AU) 2 4 6 Figure 25. circled in red. you get the plot below for a mass of Jupiter = 10*M_j. 10 times it’s actual value. that is. Simulation of solar system containing Jupiter and Earth By changing the value of M_j.

Kevin Berwick Page 51 . Simulation of solar system containing Jupiter and Earth. If the mass of Jupiter is increased to 1000 times the actual value and the perturbation of Jupiter on the Sun is ignored then we get the plot below.Jupiter Earth 6 4 2 y(AU) 0 -2 -4 -6 -6 -4 -2 0 x(AU) 2 4 6 Figure 26. Jupiter mass is 10 X actual value.3 body simulation .

Jupiter mass is 1000 X actual value. ignoring perturbation of the Sun.13.3 body simulation .Jupiter Earth 6 4 2 y(AU) 0 -2 -4 -6 -6 -4 -2 0 x(AU) 2 4 6 Figure 27. This is possibly due to the fact that the trajectory is very sensitive to the initial conditions.Simulation of solar system containing Jupiter and Earth. Kevin Berwick Page 52 . Note that this is somewhat different to Fig 4.

where v is the velocity of the Earth. Saturn.6 Chaotic tumbling of Hyperion The model of the moon consists of two particles. differential equations. first order. This orbits around a massive object. First we need to recall the maths in Section 4. We need suitable units of mass. For circular motion we know that the centripetal force is given by . Now. Since the velocity of Earth is 2πr/yr=2π1AU/yr Kevin Berwick Page 53 . write each 2nd order differential equations as two.4. Not that the Earth’s orbit is circular. m1 and m2 joined by a massless rod.1. we used in order to calculate the motion of the Earth around the Sun. at the origin. We need to extend our original planetary motion program to include the rotation of the object.

( ) ( )( ) Here is the code for the motion of Hyperion. from the analysis of the motion of Hyperion. This gave a circular orbit.So. The initial velocity in the y direction was 1 HU/Hyperion year as explained in the book. Note from the results that the tumbling is not chaotic under these conditions. Now. and noting that as noted in the book. ( )( ) So we need to add two more difference equations to our program. the difference equation set using the Euler Cromer method is We can use this equation set to model the motion of the centre of mass of Hyperion. Kevin Berwick Page 54 .

1). % Calculate new angular velocity omega and angle theta. x(1)=1.(4*pi^2*y(i)*dt)/(r_c(i)^3). y(1)=0.6 by Kevin Berwick npoints=100000. v_x(1)=0. omega=zeros(npoints. r_c=zeros(npoints. Note that GMsaturn=4*pi^2. %We need to adjust theta after each iteration so as to keep it between Kevin Berwick Page 55 .1). y=zeros(npoints.% % % % % % % Simulation of chaotic tumbing of Hyperion.update positions of centre of mass of Hyperion using NEWLY calculated velocities x(i+1)=x(i)+v_x(i+1)*dt. v_y(i+1)=v_y(i) .1). v_y=zeros(npoints.1).0001.y(i)*cos(theta(i)). % Compute new velocities in the x and y directions v_x(i+1)=v_x(i) . % time step in years time=zeros(npoints. the moon of Saturn . %Theta is an angular variable so values of theta that differ by 2*pi correspond to the same position. v_y(1)=2*pi. Term2=x(i)*sin(theta(i)).1).1). Use Euler Cromer method based on 'Computational Physics' book by N Giordano and H Nakanishi Section 4. v_x=zeros(npoints. velocity and angle and angular velocity of % centre of mass x=zeros(npoints.1). y(i+1)=y(i)+v_y(i+1)*dt. Term3=x(i)*cos(theta(i)) +y(i)*sin(theta(i)). theta=zeros(npoints. omega(i+1)=omega(i) -Term1*Term2*Term3*dt.1). see book for details Term1=3*4*pi^2/(r_c(i)^5). % Create arrays to store position. % Euler Cromer Step . % initialise position of centre of mass of Hyperion in HU % initialise velocity of centre of mass of Hyperion % initialise theta and omega of Hyperion for i= 1:npoints-1. % loop over the timesteps r_c(i)=sqrt(x(i)^2+y(i)^2).(4*pi^2*x(i)*dt)/(r_c(i)^3). dt = 0.

time(i+1)=time(i)+dt.1. end. title('theta versus time for Hyperion'). subplot(2. end. axis([0 8 0 15]).1. xlabel('time(year)').1). The initial velocity in the y direction was 1 HU/Hyperion year. elseif (temporary_theta_i_plus_1 > pi) temporary_theta_i_plus_1= temporary_theta_i_plus_1-2*pi.'-g').Motion of Hyperion. title('omega versus time for Hyperion'). ylabel('omega(radians/yr)'). if (temporary_theta_i_plus_1 < -pi) temporary_theta_i_plus_1= temporary_theta_i_plus_1+2*pi. theta. We do that here temporary_theta_i_plus_1= theta(i)+omega(i+1)*dt. ylabel('theta(radians)'). xlabel('time(year)'). Note from the results that the tumbling is not chaotic under these conditions. plot(time. axis([0 8 -4 4]). This gave a circular orbit. subplot(2.'-k'). % Update theta array theta(i+1)=temporary_theta_i_plus_1. Kevin Berwick Page 56 . theta versus time for Hyperion 4 theta(radians) 2 0 -2 -4 0 1 2 4 5 time(year) omega versus time for Hyperion 3 6 7 8 15 omega(radians/yr) 10 5 0 0 1 2 3 4 time(year) 5 6 7 8 Figure 28.2). omega.%+/-pi for plotting purposes. plot(time.

dt = 0. v_y(i+1)=v_y(i) .1). v_x(1)=0. r_c=zeros(npoints. This gave an elliptical orbit.1). % time step in years time=zeros(npoints. omega=zeros(npoints. % Compute new velocities in the x and y directions v_x(i+1)=v_x(i) .update positions of centre of mass of Hyperion using NEWLY calculated velocities x(i+1)=x(i)+v_x(i+1)*dt. % Euler Cromer Step . % Create arrays to store position.If we change the initial velocity in the y direction to 5 HU/Hyperion year as explained in the book. velocity and angle and angular velocity of % centre of mass x=zeros(npoints.1). Here is the new code and below this code are the results from running this code. Note that GMsaturn=4*pi^2. Term3=x(i)*cos(theta(i)) +y(i)*sin(theta(i)).1).1). Term2=x(i)*sin(theta(i)). Kevin Berwick Page 57 . % initialise position of centre of mass of Hyperion in HU % initialise velocity of centre of mass of Hyperion % initialise theta and omega of Hyperion for i= 1:npoints-1. x(1)=1.1). Note that now the motion is chaotic.y(i)*cos(theta(i)). Use Euler Cromer method based on 'Computational Physics' book by N Giordano and H Nakanishi Section 4. y=zeros(npoints.1). % Calculate new angular velocity omega and angle theta.(4*pi^2*x(i)*dt)/(r_c(i)^3). y(1)=0. the moon of Saturn . v_y=zeros(npoints.(4*pi^2*y(i)*dt)/(r_c(i)^3).6 by Kevin Berwick npoints=100000. theta=zeros(npoints. % % % % % % % Simulation of chaotic tumbing of Hyperion. % loop over the timesteps r_c(i)=sqrt(x(i)^2+y(i)^2). see book for details Term1=3*4*pi^2/(r_c(i)^5). v_x=zeros(npoints.1). y(i+1)=y(i)+v_y(i+1)*dt. v_y(1)=5.0001.

theta. xlabel('time(year)'). time(i+1)=time(i)+dt. omega. title('omega versus time for Hyperion'). axis([0 10 -4 4]). plot(time. axis([0 10 -20 60]). ylabel('omega(radians/yr)'). We do that here temporary_theta_i_plus_1= theta(i)+omega(i+1)*dt. % Update theta array theta(i+1)=temporary_theta_i_plus_1. end.1. subplot(2. xlabel('time(year)').1. ylabel('theta(radians)').omega(i+1)=omega(i) -Term1*Term2*Term3*dt. plot(time. elseif (temporary_theta_i_plus_1 > pi) temporary_theta_i_plus_1= temporary_theta_i_plus_1-2*pi. end. subplot(2.'-g'). %Theta is an angular variable so values of theta that differ by 2*pi correspond to the same position. title('theta versus time for Hyperion').'-k').2). %We need to adjust theta after each iteration so as to keep it between %+/-pi for plotting purposes. if (temporary_theta_i_plus_1 < -pi) temporary_theta_i_plus_1= temporary_theta_i_plus_1+2*pi.1). Kevin Berwick Page 58 .

Motion of Hyperion. The initial velocity in the y direction was 5 HU/Hyperion year. Kevin Berwick Page 59 .theta versus time for Hyperion 4 2 theta(radians) 0 -2 -4 0 1 2 3 4 5 time(year) 6 7 8 9 10 omega versus time for Hyperion 60 omega(radians/yr) 40 20 0 -20 0 1 2 3 4 5 time(year) 6 7 8 9 10 Figure 29. Note from the results that the tumbling is chaotic under these conditions. This gave a circular orbit.

end. Potentials and Fields 5. % While we have not met the convergence criterion and the number of loops is <10 so that we give the relaxation % algorithm time to converge while (delta_V_new > 49e-5 & loops < 10). [V_new.1 % by Kevin Berwick % % Load array into V [V] =Initialise_V_Jacobi_metal_box. Laplace_calculate_Jacobi_metal_box 2. drawnow. % run update routine and estimate convergence %Initialise loop counter loops=1. 3. delta_V_new]=Update_V_Jacobi_Metal_box(V_new).1 Solution of Laplace’s equation using the Jacobi relaxation method. % draw the surface using the mesh function mesh (V_new). delta_V_new]=Update_V_Jacobi_Metal_box(V). title('Potential Surface'). There are 3 files required here 1.5. Update_V_Jacobi_Metal_box %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Jacobi method to solve Laplace equation % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 5. loops=loops+1. [V_new. Initialise_V_Jacobi_metal_box. Kevin Berwick Page 60 . % insert a pause here so we see the evolution of the potential % surface pause(1).

% Calculate delta_V_new value. % clear variables clear.j)+V(i+1. the cumulative change in V during this update call. -1 0 0 0 0 0 1.j)-V(i. for i=2:row_size -1. end. % This function takes a matrix V and applies Eq 5. -1 -0. element by element computing Eq 5. the total accumulated amount by which the elements % of the matrix have changed row_size = size(V. -1 0 0 0 0 0 1. % Move along the matrix.2). -1 0 0 0 0 0 1. ignoring % boundaries for j =2:column_size-1. delta_V_new=0. end.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % Jacobi method to solve Laplace equation based on 'Computational Physics' book by N Giordano and H Nakanishi Section 5. It returns the % processed matrix to the calling function. column_size=size(V.10. delta_V_new] = Update_V_Jacobi_Metal_box(V). -1 0 0 0 0 0 1.67 -0. % preallocate memory for speed V_new=V. V_new(i.67 -0.33 0 0.33 0 0.j+1))/4.67 1.33 0. Only the values inside the boundaries are changed. to test for convergence delta_V_new=delta_V_new+abs(V_new(i.1 by Kevin Berwick % This function creates the intial voltage array V function[V] =Initialise_V_Jacobi_metal_box. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ V_new.j)). together with the value of delta_V.67 1].1).10 to it. V = [-1 -0.j-1)+V(i. -1 0 0 0 0 0 1. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Kevin Berwick Page 61 .j)+V(i.j) = (V(i-1.33 0.

5 0 -0.5 -1 8 6 4 2 0 0 2 6 4 8 Figure 30. Equipotential surface for geometry depicted in Figure 5.Potential Surface 1 0.2 in the book Kevin Berwick Page 62 .

end. while (delta_V_new>4e-5 | loops < 20). axis([0 20 0 20 0 1]).'phong').'interp'). This is the solution for the situation shown in Figure 5.'interp'. title('Potential Surface'). Initialise_prism 3. together with the output. % run update routine and estimate convergence [V_new.'FaceColor'. There are 3 files required here and the code is listed in order below.4. [V_new. mesh (V_new.'FaceColor'. % draw the surface using the mesh function % mesh (V_new. Kevin Berwick Page 63 . %Initialise loop counter loops=0. drawnow.'FaceLighting'.1.'none'. % While we have not met the convergence criterion and the number of loops is <10 so that we give the relaxation % algorithm time to converge % while (delta_V_new > & loops < 30).'EdgeColor'.5). metallic inner conductor.5. delta_V_new]=Update_prism(V_new). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Jacobi method to solve Laplace equation based on 'Computational Physics' book by N Giordano and H Nakanishi Section 5. delta_V_new]=Update_prism(V).1 Solution of Laplace’s equation for a hollow metallic prism with a solid. loops=loops+1. 1.1 % by Kevin Berwick % % Load array into V [V] =Initialise_prism. Laplace_prism 2. Update_prism %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Jacobi method to solve Laplace equation % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 5.1 by Kevin Berwick % % % % % % % This function creates the intial voltage array V function[V] =Initialise_prism. % insert a pause here so we see the evolution of the potential % surface pause(0.

V = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 000000 01 1 1 1 1 10000000 000000 01 1 1 1 1 10000000 00000001 1 1 1 1 10000000 000000 01 1 1 1 1 10000000 000000 01 1 1 1 1 10000000 000000 01 1 1 1 1 10000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 ].% clear variables clear. Kevin Berwick Page 64 .

j) ~=1. delta_V_new] = Update_prism(V).10 to it. % This function takes a matrix V and applies Eq 5. It returns the % processed matrix to the calling function.j)+V(i. % preallocate memeory for speed V_new=V.2). Only the values inside the boundaries are changed. together with the value of delta_V. leave value unchanged V_new(i. column_size=size(V.10. % Do not update V in metal bar if V(i.j) = (V(i-1. delta_V_new=0.j)+V(i+1. end.j)-V(i. calculate V_new and % delta_V_new to test for convergence V_new(i. element by element computing Eq 5. % If the value of V is not =1.1). % Move along the matrix.j-1)+V(i.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ V_new.j)=V(i. ignoring % boundaries for j =2:column_size-1. for i=2:row_size -1.j+1))/4.j)) else % otherwise. end. end.j). Kevin Berwick Page 65 . the total accumulated amount by which the elements % of the matrix have changed row_size = size(V. delta_V_new=delta_V_new+abs(V_new(i.

8 0. % While we have not met the convergence criterion and the number of loops is <20 so that we give the relaxation % algorithm time to converge while (delta_V_new>400e-5 | loops < 20). delta_V_new]=capacitor_update(V_new).2 Solution of Laplace’s equation for a finite sized capacitor This is the solution for the situation shown in Figure 5.7. 1. %Initialise loop counter loops=1. together with the output. 5.6 0. capacitor_update % % Jacobi method to solve Laplace equation % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 5.6 and 5. capacitor_laplace 2. loops=loops+1.2 0 20 15 10 5 0 0 5 15 10 20 Figure 31. % run update routine and estimate convergence [V_new. [V_new. capacitor_initialise 3.Potential Surface 1 0. There are 3 files required here and the code is listed in order below.1.4 0. Kevin Berwick Page 66 . delta_V_new]=capacitor_update(V).1 % by Kevin Berwick % % Load array into V [V] =capacitor_initialise.Equipotential surface for hollow metallic prism with a solid metallic inner conductor held at V=1.

5). Kevin Berwick Page 67 . title('Potential Surface'). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % Jacobi method to solve Laplace equation based on 'Computational Physics' book by N Giordano and H Nakanishi Section 5. axis([0 20 0 20 -1 1]). % clear variables clear.'Facecolor'. % insert a pause here so we see the evolution of the potential % surface pause(0. end.'interp'). V = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 ]. drawnow.% draw the surface using the mesh function mesh (V_new.1 by Kevin Berwick % This function creates the intial voltage array V function[V] =capacitor_initialise.

% If the value of V is not =1 or -1. column_size=size(V.10 to it. Only the values inside the boundaries are changed. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Kevin Berwick Page 68 . end.j-1)+V(i.10. calculate V_new and % cumulative delta_V_new to test for convergence V_new(i.2). leave value unchanged V_new(i. end. for i=2:row_size -1. % preallocate memory for speed V_new=zeros(row_size. delta_V_new=0. delta_V_new] = capacitor_update(V).j)+V(i+1. % This function takes a matrix V and applies Eq 5.1).j)~=1 & V(i. together with the value of delta_V.j+1))/4. delta_V_new=delta_V_new+abs(V_new(i.j)=V(i.j)-V(i. % Move along the matrix. % Do not update V on the plates if V(i.j)+V(i.j)) else % otherwise.j) = (V(i-1. element by element computing Eq 5. ignoring % boundaries for j =2:column_size-1. It returns the % processed matrix to the calling function.j) ~=-1.j). column_size). end.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ V_new. the total accumulated amount by which the elements % of the matrix have changed row_size = size(V.

5 -1 20 15 10 5 0 0 5 10 15 20 Figure 32. Kevin Berwick Page 69 . Equipotential contours near a finite sized capacitor.Potential Surface 1 0.Equipotential surface for a finite sized capacitor.5 0 -0. Potential Surface 20 18 16 14 12 10 8 6 4 2 0 0 2 4 6 8 10 12 14 16 18 20 Figure 33.

2)^2 | loops < 20). % draw the surface using the mesh function mesh(V. title('Potential Surface'). end.5. %Initialise loop counter loops=1. axis([0 60 0 60 -1 1]). together with the output. loops=loops+1 [V. capacitor_initialise_SOR 3. delta_V_total]=capacitor_update_SOR(V). 1. drawnow. % insert a pause here so we see the evolution of the potential % surface pause(0. Kevin Berwick Page 70 .5).Note convergence for 1e-5 * No of sites while (delta_V_total>1e-5*size(V.1. capacitor_update_SOR % % SOR method to solve Laplace equation % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 5.1 % by Kevin Berwick % % Load array into V [V] =capacitor_initialise_SOR. capacitor_laplace_SOR 2.'Facecolor'. % run update routine and estimate convergence [V.'interp').7 and the Successive Over Relaxation Algorithm There are 3 files required here and the code for the SOR algorithm used in order to sole Laplaces equation for the capacitor is listed in order below. % While we have not met the convergence criterion and the number of loops is <20 so that we give the relaxation % algorithm time to converge.3 Exercise 5. delta_V_total]=capacitor_update_SOR(V).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SOR method to solve Laplace equation % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 5. % clear variables clear. V = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 ]. Kevin Berwick Page 71 .1 % by Kevin Berwick % % This function creates the intial voltage array V function[V] =capacitor_initialise_SOR.

% grid size.2). % add a multiple of delta_V to the original value in the cell. 'over-relax' % Update convergence metric for this update delta_V_total= delta_V_total+abs(delta_V).%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [V. ignoring % boundaries for i=2:row_size -1.j).j) ~=-1.14.j+1))/4. Kevin Berwick Page 72 .j)~=1 & V(i. column_size=size(V. element by element computing Eq 5. calculate the new value of the cell and % delta_V_new to test for convergence V_star = (V(i-1. % If the value of V is not =1 or -1.1). % Move along the matrix. that is.% delta_V is the difference between the Gauss Siedel updated value for the cell % and the original value of the cell % Update Matrix V . end. % This function takes a matrix V and applies Eq 5. in a raster scan.j).j)+V(i. in place. the total accumulated amount by which the elements % of the matrix have changed row_size = size(V. Only the values inside the boundaries are changed. delta_V_total] = capacitor_update_SOR(V). % use recommended value for book for alpha % intialise convergence metric delta_V_total=0.14 to it. L=column_size. together with the value of delta_V. It returns the % processed matrix to the calling function.j)=alpha*delta_V+V(i. for a square grid 20 X 20 . % This is the Gauss Siedel updated value for the cell delta_V =V_star-V(i. end. end.j-1)+V(i. L=20 alpha = 2/(1+pi/L). % Do not update V on the plates if V(i. so latest values will be used % for SOR V(i.j)+V(i+1. for j =2:column_size-1.

for the L X L grids shown.6 0. L N Jacobi N_SOR 20 (400 elements) 128 33 40 (1600 elements) 492 60 60 (3600 elements) 884 84 Kevin Berwick Page 73 .6 -0. it creates a movie of the potential surface.4 -0.8 0. Potential Surface 1 0.4 0. The convergence criterion was that the simulation was halted when the difference in successively calculated surfaces was less than 10 -5 per site.2 0 -0.Note that when you run the SOR code. You can see waves moving across the potential surface as the surface ‘over relaxes’ and then corrects itself. The results are summarised in the Table below.Equipotential surface in region of a simple capacitor as calculated using the SOR code for a 60 X 60 grid. The code was ran for both the Jacobi method and the SOR method.8 -1 60 50 40 30 20 10 0 0 20 10 30 40 50 60 Figure 34. The convergence criterion was that the simulation was halted when the difference in successively calculated surfaces was less than 10-5 per site.2 -0.

The convergence criterion was that the simulation was halted when the difference in successively calculated surfaces was less than 10 -5 per site. The convergence criterion was that the simulation was halted when the difference in successively calculated surfaces was less than 10 -5 per site. No of iterations of SOR method vs L 90 80 70 N SOR 60 50 40 30 20 25 30 35 40 L 45 50 55 60 Figure 36. Kevin Berwick Page 74 .Number of iterations required for Jacobi method vs L for a simple capacitor.Here are plots comparing the number of iterations required to give the same accuracy for each algorithm. Number of iterations of Jacobi method vs L2 900 800 700 600 N Jacobi 500 400 300 200 100 0 500 1000 1500 2000 L2 2500 3000 3500 4000 Figure 35.Number of iterations required for SOR method vs L for a simple capacitor.

The matrix is 3D of length 20 clear. shading interp. delta_x=0. % spatial step size convergence_per_site=1e-6. as outlined in Section 5.2)^3 || loops < 20). lighting phong.rho. grid on. loops=loops+1.2 There are 3 files here 1. % While we have not met the convergence criterion and the number of loops is <20 so that we give the % algorithm time to converge while (delta_V_new>convergence_per_site*size(V_matrix. rho. rho=zeros(20. delta_V_new]=point_charge_update(V_matrix. view(3). light. point_charge_Jacobi 2. end.20).2. % place charge of 1 at centre of box shaped volume % Create Potential matrix V_matrix=zeros(20. % take a cutline across the slice surface and plot subplot(1.2.2. surf(slice).10. % Create box to contain charge rho(10.2). delta_x). point_charge_update 3. camlight('left').10)=(1/delta_x^3). :. delta_V_new]=point_charge_update(V_new. delta_x). [V_new. r]=point_charge_coulomb. title('Potential'). axis on. % run Update routine for the first time and calculate convergence metric [V_new. % Visualise result by taking a slice half way up the cube. %Initialise loop counter loops=1. % Run the routine to plot the potential as calculated analytically using Coulomb's Law [coulomb.5. 10).20. slice = V_new(:. Kevin Berwick Page 75 .20).2 Potentials and fields near Electric charges.20.1). subplot(1. point_charge_coulomb % Jacobi method to solve Poisson's equation % based on 'Computational Physics' book by N Giordano and H Nakanishi % This code creates the intial potential and charge 3D matrices and % definitions. Poisson’s Equation Here we use the standard Jacobi method to calculate the potential surface near a point charge in the centre of a box.

Note the use of a.c)*delta_x^2/6 .c) = (V(a-1.b-1.b. rescale=[0:0.b. end. title('Numerical result and Coulombs Law') hold on. end.2).coulomb.c-1))/6 + rho(a. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [V_new. % the total accumulated amount by which the elements % of the matrix have changed x_size = size(V. together with the value of delta_V.1).j.cut_slice=slice(10. % calculate V_new and cumulative delta_V_new to test for convergence V_new(a.c)-V(a.3).c+1)+V(a. delta_V_new] = point_charge_update(V. plot(rescale. delta_V_new=delta_V_new+abs(V_new(a.'Coulomb'). y_size = size(V.'og').b. together with the value of delta_V. z_size = size(V.20.k since i and j are % already defined in MATLAB for c=2:z_size-1.b. y_size.b.c)). rho. element by element computing Eq 5. ylabel('V').c)+V(a. legend('Numerical results'.x] = point_charge_coulomb % This function takes a matrix V and solves Poisson's equation.c)+V(a. % the total accumulated amount by which the elements % of the matrix have changed Kevin Berwick Page 76 . for b =2:y_size-1.b. It needs rho and delta_x %the charge distribution and spatial step size also. for a=2:x_size -1. delta_V_new=0. z_size). It returns the % processed matrix to the calling function.c)+V(a. It needs rho and delta_x %the charge distribution and spatial step size also.'k').c instead of i. axis([0 2 0 0.b. end. % Plot Coulomb's law result for comparison plot(r. xlabel('x').b. It returns the % processed matrix to the calling function. % Move along the matrix. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [V.b.c)+V(a+1.b+1. delta_x). ignoring % boundaries. % preallocate memory for speed V_new=zeros(x_size.2:2]. % This function takes a matrix V and solves Poisson's equation.8]).cut_slice. 10:20).

x=[0:0.05:2]; % Since q/epsillon_zero=1 V=1./(4*pi*x);

Here is the result of running the code

Potential 0.8

Numerical result and Coulombs Law Numerical results Coulomb 0.7

1.4 1.2 1 0.5 0.8 0.6 0.4 0.3 0.2 0 20 15 10 10 5 0 0 5 0 0 0.2 0.4 0.6 0.8 1 x 1.2 1.4 1.6 1.8 2 15 20 0.1 0.6

0.4

V

0.2

Figure 37. Equipotential surface near a point charge at the center of a 20X20 metal box. The Jacobi relaxation method was used . The plot on the right compares the numerical and analytical (as obtained from Coulomb’s Law).

Kevin Berwick

Page 77

6. Waves
6.1 Waves on a string

Here we simulate the motion of a string using the wave equation. There are 2 files here 1. waves 2. propagate
% Solution of wave equation for string % based on 'Computational Physics' book by N Giordano and H Nakanishi clear; string_dimension=100; % Preallocate matrices for speed; x=1/string_dimension:1/string_dimension:1; x_scale=1:1:string_dimension; y_next =zeros(1,string_dimension); % Initialise string position k=1000; x_0=0.3; initial_position=exp(-k.*(x-x_0).^2); y_current =initial_position; y_previous = initial_position; for time_step = 1:500; [y_next]=propagate(y_current, y_previous); y_previous=y_current; y_current=y_next; % pause(0.1); clf; plot(x_scale/string_dimension, y_current,'r'); title('Waves on a string - fixed ends'); xlabel('distance'); ylabel('Displacement'); axis([0 1 -1 1]); hold on; drawnow; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [y_next] = propagate(y_current, y_previous) r=1; % since r=c*delta_t/delta_x and for the Figure 6.2 example delta_t=delta_x/c, giving r=1 M=size(y_current,2); % Vector size = number of columns % there are 3 vectors containing positional information for the whole % string,; y_new, y_current and y_old % preallocate memory for speed % This function calculates the new shape of the string after one time step % HERE IS THE ORIGINAL CODE % for i=2:M-1; %This loop index takes care of the fact that the boundaries are fixed % y_next(i) = 2*(1-r^2)*y_current(i).... % -y_previous(i).... % +r^2*(y_current(i+1)+y_current(i-1)); % end; % HERE IS THE VECTORISED CODE, WHICH IS MORE EFFICIENT

Kevin Berwick

Page 78

y_next=zeros(1,M); i=2:1:M-1; %This loop index takes care of the fact that the boundaries are fixed y_next(i) = 2*(1-r^2)*y_current(i).... -y_previous(i).... +r^2*(y_current(i+1)+y_current(i-1));

Waves on a string - fixed ends 1 0.8 0.6 0.4

Displacement

0.2 0 -0.2 -0.4 -0.6 -0.8 -1

0

0.1

0.2

0.3

0.4

0.5 0.6 distance

0.7

0.8

0.9

1

Figure 38. Waves propagating on a string with fixed ends

Kevin Berwick

Page 79

Kevin Berwick Page 80 .

y_current=y_next.time_loops). y_current =initial_position. which makes delta_t = delta_x/c = 0. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [y_next] = propagate_free(y_current. the string is free at the ends. for time_step = 1:time_loops.01/300 = 3. delta_t=3. string_dimension=100.1 Waves on a string with free ends Here we simulate the motion of a string using the wave equation. xlabel('distance'). time=time+delta_t. time=initial_time.33e-5. giving r=1. delta_x=0.time_loops). title('Waves on a string . [y_next]=propagate_free(y_current.2). y_previous = initial_position.2 example % delta_t=delta_x/c.string_dimension). propagate_free % Solution of wave equation with free ends for string % based on 'Computational Physics' book by N Giordano and H Nakanishi clear.1. time_loops=1500. clf. y_new. y_current and y_old Kevin Berwick Page 81 . y_previous).6. (imagine the string tied to a massless ring which slides frictionlessly up and down a vertical pole). initial_time=0. y_next =zeros(1. axis([0 1 -1 1]).*(x-x_0). end. x_0=0. ylabel('Displacement'). r=1.. initial_position=exp(-k. elapsed_time=zeros(1.01. plot(x_scale/string_dimension. M=size(y_current. x=1/string_dimension:1/string_dimension:1. drawnow.^2). % Initialise string position k=1000. signal_data=zeros(1.5. y_current. however. waves_free 2. % Vector size = number of columns % there are 3 vectors containing positional information for the whole % string. hold on.'r').free ends'). y_previous) % c=300.33e-5 % since r=c*delta_t/delta_x and for the Figure 6. y_previous=y_current. x_scale=1:1:string_dimension. % Preallocate matrices for speed. There are 2 files here 1.

M).... i=2:1:M-1. % +r^2*(y_current(i+1)+y_current(i-1)).. %This index ignores the boundaries y_next(i) = 2*(1-r^2)*y_current(i).... % -y_previous(i)... % Update position of free ends to those of nearest neighbours y_next(1)=y_next(2). y_next(M)=y_next(M-1). % end. %This loop index takes care of the fact that the boundaries are fixed % y_next(i) = 2*(1-r^2)*y_current(i).. % HERE IS THE VECTORISED CODE. WHICH IS MORE EFFICIENT y_next=zeros(1..% preallocate memory for speed % This function calculates the new shape of the string after one time step % HERE IS THE ORIGINAL CODE % for i=2:M-1. +r^2*(y_current(i+1)+y_current(i-1)). Kevin Berwick Page 82 . -y_previous(i)..

x_scale=1:1:string_dimension.2. end. % Initialise string position k=1000.^2). % plot displacement at 5 percent from left end of the string % using suitable scaling plot(elapsed_time.time_loops).2). propagate % Solution of wave equation for string % based on 'Computational Physics' book by N Giordano and H Nakanishi % clear. subplot(2. elapsed_time=zeros(1. y_current =initial_position. subplot(2. axis([0 1 -1 1]). time=initial_time. f_sample=1/delta_t. title('Waves on a string . x=1/string_dimension:1/string_dimension:1. string_dimension=100. clf.*(x-x_0).time_loops). hold on. drawnow. y_current. y_previous).6. time_loops=1500. xlabel('distance'). delta_t=3. [y_next]=propagate(y_current. y_current=y_next. plot(x_scale/string_dimension. ylabel('Displacement'). There are 2 files here 1. elapsed_time(time_step)=time.string_dimension). %%%%%%% % Record displacement at 5 percent from left end of the string for future plot signal_data(time_step)=y_current(5).'r').signal_data).2.33e-5.fixed ends'). title('Signal from a string'). y_previous=y_current. time=time+delta_t. y_next =zeros(1. waves 2.5. initial_position=exp(-k.2 Frequency spectrum of waves on a string Here we simulate the motion of a string using the wave equation.1). for time_step = 1:time_loops. % Preallocate matrices for speed. signal_data=zeros(1. x_0=0. y_previous = initial_position. Kevin Berwick Page 83 . initial_time=0.

Note that 1500 samples are played in 0. It would be nice to signal the end of program execution with the tone that would be heard from % this string. % only half points are unique due to nature of FFT. is equal % to the sum of the real and imaginary components of the % FFT. are unique and should not be multiplied by 2. title('Power spectrum').3333e-05 = 30 kHz. end % Calculate scaled frequency scale f = (0:Num_Unique_Pts-1)*f_sample/NFFT. ylabel('Power(au)').1/3. xlabel('frequency (Hz)'). % Power spectrum is symmetric so plot first half plot(f.3333e-5 =30 kHz sound(signal_data. ylabel('Displacement(au)'). of points in DFT=Next power of 2 up from length of signal_data fft_value = fft(signal_data. therefore.xlabel('time (s)').The sampling frequency is. we multiply the power_spectrum by 2 to keep the same energy. NFFT = 2^(nextpow2(length(signal_data))). You can multiply the result of the FFT by its complex % conjugate in order to calculate it. % The DC component and Nyquist component.05/1500 = 3.3). if rem(NFFT. % No. 2) % odd NFFT excludes Nyquist point power_spectrum(2:end) = power_spectrum(2:end)*2. The power spectral density. else power_spectrum(2:end -1) = power_spectrum(2:end -1)*2. % a measurement of the energy at various frequencies. % therefore each sample should be played for 0. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Kevin Berwick Page 84 . % Since we dropped half the FFT.3333e-05 seconds.05s.NFFT).'g').power_spectrum. axis([0 3000 0 6]). % throw away half the points %Calculate the scaled power spectrum normalised by dividing % by the length of the signal data vector power_spectrum= fft_value.*conj(fft_value)/(length(signal_data)). % Perform (NFFT point) DFT padding out with zeros so length of fft_value is NFFT Num_Unique_Pts=ceil((NFFT+1)/2). You would use the displacement from the vector 'signal_data' for this. % Generate FFT and calculate the power spectrum.. if it exists. % So the sampling rate is 1/3. f_sample=1/delta_t.2. subplot(2. 30e3). Calculate number fft_value=fft_value(1:Num_Unique_Pts). % Matlab offers the facility to play sounds.

035 0...6 distance 0.function [y_next] = propagate(y_current. y_previous) % c=300. % end....015 0. % HERE IS THE VECTORISED CODE.8 0.01 0. % +r^2*(y_current(i+1)+y_current(i-1)). % Vector size = number of columns % there are 3 vectors containing positional information for the whole % string.03 time (s) 0.045 0. giving r=1..M).05 Power spectrum 6 5 4 Power(au) 3 2 1 0 0 500 1000 1500 frequency (Hz) 2000 2500 3000 Kevin Berwick Page 85 .5 Displacement(au) Displacement 0 0 -0.7 0.005 0. i=2:1:M-1..04 0.2 0... y_new.. WHICH IS MORE EFFICIENT y_next=zeros(1.01. delta_x=0.5 0.2). r=1. %This loop index takes care of the fact that the boundaries are fixed y_next(i) = 2*(1-r^2)*y_current(i).33e-5 % since r=c*delta_t/delta_x and for the Figure 6.. which makes delta_t = delta_x/c = 0.01/300 = 3.025 0.. Waves on a string .5 Signal from a string 0.. +r^2*(y_current(i+1)+y_current(i-1)).02 0. % -y_previous(i).4 0. %This loop index takes care of the fact that the boundaries are fixed % y_next(i) = 2*(1-r^2)*y_current(i).fixed ends 1 0. M=size(y_current.1 0. -y_previous(i).5 -1 0 0.3 0.2 example % delta_t=delta_x/c.9 1 -0.5 0 0. y_current and y_old % preallocate memory for speed % This function calculates the new shape of the string after one time step % HERE IS THE ORIGINAL CODE % for i=2:M-1.

Figure 39. Kevin Berwick Page 86 . Signal from a vibrating string and Power spectrum. Signal excited with Gaussian pluck centred at the middle of the string and the displacement 5% from the end of the string was recorded.

7.number_of_steps). the squared displacement. end. for i=1:number_of_steps. % Accumulate value of x^2 . end. if rand<0.5. 'g'). xlabel('Step number'). x2ave=zeros(1. % Divide by number of walkers x2ave= x2ave/number_of_walkers.number_of_steps). plot(step_number_array. number_of_steps=100. step_number=zeros(1. x=x+1. y=0. for each step number x2ave(i)=x2ave(i)+x^2. Kevin Berwick Page 87 . end. ylabel('x^2').1 Random walk simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solution of random walk problem % based on 'Computational Physics' book by N Giordano and H Nakanishi % Solution by Kevin Berwick %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear. x2ave. step_number_array=[1:1:number_of_steps]. % initialise position x=0. number_of_walkers=500. Random Systems 7. else x=x-1. title('Random walk'). for r=1:number_of_walkers.

x^2 as a function of step number. Average of 500 walks. Step length = 1. Kevin Berwick Page 88 .2 x2 50 40 30 20 10 0 0 10 20 30 40 50 Step number 60 70 80 90 100 Figure 40.Random walk 100 90 80 70 60 data fit linear y = 0.96*x + 1. Also shown is a linear fit to the data.

% initialise position x=0.5. step_number_array=[1:1:number_of_steps].number_of_steps). xlabel('Step number'). else x=x-rand. x2ave=zeros(1. 'g'). plot(step_number_array. title('Random walk with random step length').1. Kevin Berwick Page 89 . the squared displacement. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solution of random walk problem % based on 'Computational Physics' book by N Giordano and H Nakanishi % Solution by Kevin Berwick %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear. end. for r=1:number_of_walkers.1 Random walk simulation with random path lengths. step_number=zeros(1. for each step number x2ave(i)=x2ave(i)+x^2. number_of_steps=100. end. ylabel('x^2'). for i=1:number_of_steps. end.7. if rand<0.number_of_steps). % Accumulate value of x^2 . x=x+rand. number_of_walkers=500. x2ave. y=0. % Divide by number of walkers x2ave= x2ave/number_of_walkers.

Also shown is a linear fit to the data. Step length = random value betwen +/-1. Average of 500 walks. Kevin Berwick Page 90 .Random walk with random step length 35 data linear fit 30 25 20 x2 15 10 5 0 0 10 20 30 40 50 Step number 60 70 80 90 100 Figure 41. x^2 as a function of step number.

We define a minimum value for this quantity here minimum_delta_E=0.01. V(100:N) =1000. % Initialise last_diverge which keeps track of the diverging trend to zero % since we don't know this direction yet last_diverge=0. % MAIN LOOP Kevin Berwick Page 91 . % initialise E E=E_initial. calculate_psi Here is the code % % % % % % Program to calculate wave function based on 'Computational Physics' book by N Giordano and H Nakanishi Section 10. Since this is the center of the well. % If delta_E is small enough then the current E is acceptable. N=200. delta_E=0.5. N). Shooting method.879. E_initial=1. % Create half the potential well V= zeros(1. One_D_Schrodinger_Shooting 2. % Create an intial vector to hold the wavefunction b= 1. Quantum Mechanics 10.1. x=(delta_x: delta_x: N*delta_x). % suggested cutoff parameter % % Implement psi_prime(0)=0 for an even parity solution by % letting psi_in(0) and psi_in(-1)=0.2 by Kevin Berwick % Initialise clear. There are 2 files here 1. we use indices 200 and 199 for these positions.005. Here we solve the time independent Schrodinger equation in one dimension for the particle in a box problem. delta_x=0.10.2 Time independent Schrodinger equation.

E=E+delta_E last_diverge=sign(psi(i+1)). ylabel('Wavefunction').V). end. % Visualise results with movie plot(x. psi(i+1)=2*psi(i)-psi(i-1)-2*(E-V(i))*delta_x^2*psi(i). % If last value of psi evaluated before % breakout from calculate_psi function and % last diverge are of different signs. E. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function to calculate wave function % based on 'Computational Physics' book by N Giordano and H Nakanishi % Section 10. drawnow.i] = calculate_psi(psi. axis([0 2 -2 2]). b. end. N.i]=calculate_psi(psi. psi. psi(2)=1.'r'). delta_x. end. if abs(psi(i+1)) > b. % Initialise psi= zeros(1.V) %This function calculates psi % Make psi_prime(0) =0 for an even parity solution. exit the loop. E. title('Square well'). N. % if psi is diverging. N). b. return.2 % by Kevin Berwick % function [psi. Kevin Berwick Page 92 . if sign(psi(i+1))~=sign(last_diverge). psi(1)=1. delta_x. pause(0. turn % round direction of varying E and halve its % value delta_E=-delta_E/2.while abs(delta_E)>minimum_delta_E. end. for i=2:N-1. % Calculate wavefunction [psi.5). xlabel('distance').

delta_t=0.5 by Kevin Berwick % Initialise and set up initial waveform clear.5 0 -0.4.Square well 2 1.8 1 1. Kevin Berwick Page 93 . 10. k_0=500.5 1 0.5 Wavepacket construction This is a little program to illustrate wavepacket construction.2 0.2. % % % % % % Program to illustrate wavepacket construction based on 'Computational Physics' book by N Giordano and H Nakanishi Section 10. Wavefunctions are not normalised.5 -2 Wavefunction 0 0.4 1.5 -1 -1. The value of Vo used was 1000 giving ground-state energy of 1.2 distance 1. Analytical value is 1. x=(0:0. The wall(s) of the box are at x=(-)1.8 2 Figure 42.2.*exp(1i*k_0*x).0005:1).^2/sigma_squared). x_0=0. C=25.6 0. psi=C*exp(-(x-x_0).6 1. delta_x=0.23.233. sigma_squared=1e-3. Here is the code. subplot(2.4 0.0005.1). Calculated wavefunction using the shooting method.

3).7 0.'r').3 0.2. ko = 500.7 0.6 0.8 0. subplot(2.6 0.(conj(psi).*psi).plot(x. title('Probability of finding particle ').imag(psi).4 0. sigma^2=0. x0=0.9 1 10 0 -10 -20 -30 0 0.001. xlabel('distance').4 0. xlabel('distance'). Real part of wavefunction 30 20 30 20 Imaginary part of wavefunction Re(wavefunction) 10 0 -10 -20 -30 Im(wavefunction) 0 0. ylabel('Re(wavefunction)').2).8 0.2 0. plot(x.2 0.7 0.3 0. title('Imaginary part of wavefunction'). title('Real part of wavefunction ').2.9 1 Figure 43.5 distance 0.4 0.8 0. ylabel('Im(wavefunction)'). 'b').9 1 Probability of finding particle 700 600 500 psi*conj(psi) 400 300 200 100 0 0 0. Kevin Berwick Page 94 .3 0.4.'k'). subplot(2.6 0.5 distance 0. Composition of wavepacket.1 0. ylabel('psi*conj(psi)').5 distance 0. xlabel('distance').1 0. plot(x.2 0.1 0.real(psi).

% Build a potential cliff . V=0. % Discretisation parameters delta_x=1e-3.N). Representative results for a potential wall and cliff are presented . time_dep_SE_1D. A variety of scenarios can be modelled using this code. sigma_squared=1e-3.10. I_initial=imag(psi).5 % % by Kevin Berwick %% % % % Initialise and set up initial waveform clear. Here we solve the time dependent Schrodinger equation in one dimension. N=1000. Create a region with a cliff at x=0. to the right. Kevin Berwick Page 95 . x= linspace(0.6.m real_psi. C=10.3 Time Dependent Schrodinger equation in One dimension. k_0=500. % % % Extract the real and imaginary parts of the wavefunction % R_initial=real(psi). V=-1e6.m imag_psi. % % Generate an intial wavepacket % psi=C*exp(-(x-x_0).1.4. delta_t=5e-8. Leapfrog method. %% % % Program to illustrate solution of Time Dependent Schrodinger equation % % using leapfrog algorithm % % based on 'Computational Physics' book by N Giordano and H Nakanishi % % Section 10. x_0=0. To the % left. There are 3 files here.^2/sigma_squared). % Set up intial wavepacket.*exp(1i*k_0*x).

'LineWidth'. V(600:N) =-1e6. R_current=R_initial. prob_density. % Time is incremented by t=t+delta_t/2 every call. I_current=I_next.'-b'. Plot every 10 calculations for speed if rem(time_step. drawnow. % % Do the leapfrog!! % for time_step = 1:15000.N).. delta_t.. % evaluate I at (3/2)*delta_t. V). title('Reflection from cliff').. I_current. I_current. xlabel('x'). plot(x.. function [I_next]= imag_psi(N. 3*delta_t. delta_x. R_current. % Visualise results with movie. Kevin Berwick Page 96 . % evaluate R at delta_t. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Calculate the imaginary part of the wavefunction at time % t=t+delta_t/2.2).. t + 3*delta_t/2 etc % % given the value at time t. 10)== 0.. (5/2)*delta_t. end.. end.... ylabel('Probability density'). % Initial run of Im(psi) to start off leapfrog process. I_current. delta_x. % calculate psi*psi with R(t) and I(t+delta_t/2) and I(t-delta_t/2) prob_density=R_current. [I_next] = imag_psi(N. 2*delta_t. delta_t. delta_x.^2+I_next. R_current=R_next. R_current. I_current. N). R_current. V) I_next= zeros(1. % Initialise current real and imaginary parts of psi I_current=I_initial... [R_next]=real_psi(N..*I_current. delta_x. axis([0 1 0 200]).. V). R_current..V= zeros(1. delta_t... V). % t=t+delta_t/2. s=delta_t/(2*delta_x^2). delta_t.. [I_next] = imag_psi(N. % Time is incremented by t=t+delta_t/2 every call.

I_next(N)=I_next(N-1). I_next(x)=I_current(x) +s*(R_current(x+1)-2*R_current(x)+R_current(x-1)). function [R_next]= real_psi(N. R_next(x)=R_current(x) ..s*(I_current(x+1)-2*I_current(x)+I_current(x-1)). s=delta_t/(2*delta_x^2).. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Calculate the real part of the wavefunction at time t=t+delta_t. R_next(N)=R_next(N-1). delta_x. Vectorise for speed. % given the value at time t.. % t+2*delta_t etc. +delta_t*V(x).. % Boundary conditions R_next(1)=R_next(2). % Calculate the imaginary part of the wavefunction at time t=t+delta_t. % Calculate the real part of the wavefunction at time t=t+delta_t.. end. % % given the value at time t.. I_current. % given the value at time t.N). end. R_current. -delta_t*V(x).*I_current(x). % Boundary conditions I_next(1)=I_next(2). delta_t. V) R_next= zeros(1. Kevin Berwick Page 97 . Vectorise for speed. for x=2:N-1..*R_current(x).for x=2:N-1.

3 0.6 and V=1e6 for x>0. delta_t=5e-8.4. Kevin Berwick Page 98 .4 0.9 1 0 0.5 x 0.6 0.3 0.2 0.1 0.1 0. sigma_squared=1e-3. Time progresses left to right. Values used for initial wavepacket were x_0=0.9 1 Figure 44.6 0.7 0.7 0.4 0.4. Values used for initial wavepacket were x_0=0.6.7 0.8 0. sigma_squared=1e-3. Simulation used delta_x=1e-3.C=10. Simulation used delta_x=1e-3.2 0.7 0.2 0.6.2 0.5 x 0.4 0.4 0.8 0. Reflection from wall 200 180 160 140 Reflection from wall 200 180 160 140 200 180 160 140 Reflection from wall Probability density Probability density 120 100 80 60 40 20 0 120 100 80 60 40 20 0 Probability density 0 0.6 0.8 0.4 0. delta_t=5e-8.9 1 0 0.9 1 0 0.6. k_0=500. k_0=500.Reflection from cliff 200 180 160 140 Probability density Probability density Reflection from cliff 200 180 160 140 Reflection from cliff 200 180 160 140 Probability density Reflection from cliff 200 180 160 140 Probability density 120 100 80 60 40 20 0 120 100 80 60 40 20 0 120 100 80 60 40 20 0 120 100 80 60 40 20 0 0 0.5 x 0.8 0.8 0.1 0.2 0.9 1 Figure 45.1 0.5 x 0.9 1 0 0.8 0.3 0. Time progresses left to right. Wavepacket reflection from potential cliff at x=0.3 0.3 0.3 0.6 0.5 x 0.7 0.3 0.1 0.4 0.2 0. Wavepacket reflection from potential wall at x=0. The potential was V=0 for x<0.7 0. The potential was V=0 for x<0.6 0.6.7 0.4 0.1 0.1 0.5 x 0.8 0.6 and V=-1e6 for x>0.2 0.9 1 120 100 80 60 40 20 0 0 0.6 0.5 x 0.6 0.C=10.

% Set up intial wavepacket. There are 3 files here.m 3. % V(:.25. sigma_squared=0. y_0=0. delta_t=0. [x.and y-coordinates. N). Here we extend the solution of the the time dependent Schrodinger equation to two dimensions. 1. % Discretisation parameters delta_x=1/200. imag_psi_2D. 100:200)=-1e3.5. Representative results for a potential wall and cliff are presented .y] = meshgrid(a).m %% % % Program to illustrate solution of 2D Time Dependent Schrodinger equation % % using leapfrog algorithm % % based on 'Computational Physics' book by N Giordano and H Nakanishi % % Section 10. N=200. time_dep_SE_2D.4 Time Dependent Schrodinger equation in two dimensions. % % Build a mesh for the values of the probability density function a= linspace(0.5 % % by Kevin Berwick %% % % % Initialise and set up initial waveform clear. %using same resolution and scales in x and y directions. 1.N). Leapfrog method. A variety of scenarios can be modelled using this code. C=10. 100:200)=1e3.m 2. V(:. % % Create a 2D potential wall % V=zeros(N. real_psi_2D.00001.10.N). %Use meshgrid to calculate the grid matrices for the x. x_0=0. k_0=40. % Create a 2D potential cliff V=zeros(N. Kevin Berwick Page 99 .01.

psi_z=psi_stationary. 3*delta_t. R_current=R_next. % % % Initial run of Im(psi) to start off leapfrog process. grid on. view(3). plane_wave = exp(1i*k_0*x). axis on... I_current=I_next. Plot every 10 timesteps for speed if rem(time_step. colormap('bone'). surf(x. [R_next]=real_psi_2D(N. axis([0 1 0 1 0 100]).. delta_t.%+1i*k_0*y). delta_t. % Time is incremented by t=t+delta_t/2 every call. % % % % Do the leapfrog!! %% for time_step = 1:2000. R_current=R_initial. I_current. ylabel('y').. % Visualise results with movie.. zlabel('ps*psi').. delta_x. 2*delta_t. % % [I_next] = imag_psi(N. % Time is incremented by t=t+delta_t/2 every call... [I_next] = imag_psi_2D(N.^2/sigma_squared). delta_x.y.. 10)== 0. (5/2)*delta_t.^2/sigma_squared). V). Kevin Berwick Page 100 . % evaluate I at (3/2)*delta_t. I_current.% Calculate psi psi_stationary=C*exp(-(x-x_0). V). xlabel('x').*I_current..*plane_wave. % % Initialise current real and imaginary parts of psi % I_current=I_initial. % calculate psi*psi with R(t) and I(t+delta_t/2) and I(t-delta_t/2) prob_density=R_current. % % % Extract the real and imaginary parts of the wavefunction % R_initial=real( psi_z). title('Probability density function').*exp(-(y-y_0). R_current.. V). prob_density)..^2+I_next. % evaluate R at delta_t.. R_current. R_current. delta_x. I_initial=imag( psi_z). light.. delta_t.... I_current.

y-1)). Vectorise for speed. s=delta_t/(2*delta_x^2).y)+I_current(x. end. x=2:N-1.y+1)-2*R_current(x.y).. % Calculate the imaginary part of the wavefunction at time t=t+delta_t. I_current. delta_x.N). Vectorise for speed. % given the value at time t.y).y)+I_current(x.y)..lighting phong. drawnow.s*(I_current(x+1..y+1)-2*I_current(x. t + 3*delta_t/2 etc % % given the value at time t. % t+2*delta_t etc. +delta_t*V(x. function [I_next]= imag_psi_2D(N. y=2:N-1. colorbar.y) . camlight('left'). y=2:N-1.y)=I_current(x.y)=R_current(x. Kevin Berwick Page 101 .*R_current(x. R_current. delta_x. % given the value at time t.y)+R_current(x.. delta_t.*I_current(x. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Calculate the imaginary part of the wavefunction at time % t=t+delta_t/2. % % given the value at time t.y-1)). shading interp..y)+I_current(x1. R_next(x. function [R_next]= real_psi_2D(N.N). % Calculate the real part of the wavefunction at time t=t+delta_t. I_next(x.y)+R_current(x. R_current.y)-2*I_current(x. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Calculate the real part of the wavefunction at time t=t+delta_t.. delta_t. -delta_t*V(x.y)-2*R_current(x. V) I_next= zeros(N. x=2:N-1. end.y).. I_current.y) +s*(R_current(x+1.y)+R_current(x1. s=delta_t/(2*delta_x^2).. V) R_next= zeros(N.

5 0 2 0.00001.5. delta_t=0.5.5 and V=-1e3 for x>0. Values used for initial wavepacket were x_0=0.5.Wavepacket reflection from potential cliff at x=0.5 0 0 x 20 ps*psi 60 60 40 20 0 1 1 0.5 0 0 x 14 12 10 8 6 4 ps*psi y Figure 46. Kevin Berwick Page 102 .5 30 25 20 15 10 5 0 0 x y y Probability density function 16 100 80 60 40 20 0 1 1 0. y_0=0.5 0 0.C=10. k_0=40. The potential was V=0 for x<0.01. Simulation used delta_x=0.5 0 10 0. sigma_squared=0.25.005.Probability density function Probability density function 50 80 100 80 70 60 100 80 45 40 35 ps*psi 50 40 40 20 30 0 1 1 0.

Values used for initial wavepacket were x_0=0.5. delta_t=0.25.C=10.5 0 x 5 4 3 2 1 0 9 8 7 ps*psi y Figure 47.5 0 0 x 70 60 50 40 30 20 ps*psi ps*psi y y Probability density function 10 100 80 60 6 40 20 0 1 1 0. k_0=40.5 and V=1e3 for x>0.5. Simulation used delta_x=0. The potential was V=0 for x<0.00001.01. y_0=0. Wavepacket reflection from potential wall at x=0.Probability density function 80 100 80 60 40 20 0 1 1 0.5 0 10 0. sigma_squared=0. Kevin Berwick Page 103 .5 0 0 x 70 60 50 40 30 20 Probability density function 80 100 80 60 40 20 0 1 1 0.5 0 10 0.5.005.5 0 0.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer: Get 4 months of Scribd and The New York Times for just $1.87 per week!

Master Your Semester with a Special Offer from Scribd & The New York Times