Chapter 11. More Fortran Elements: Functions and Subroutines 11.1 ...
Chapter 11. More Fortran Elements: Functions and Subroutines 11.1 ...
Chapter 11. More Fortran Elements: Functions and Subroutines 11.1 ...
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
<strong>11.</strong>3.3 Subroutine Example<br />
The use of a subroutine in <strong>Fortran</strong> will be illustrated with the example of the Verlet<br />
algorithm. Recall from <strong>Chapter</strong> 5 <strong>and</strong> Assignment 1 that the velocity Verlet algorithm for<br />
numerically approximating solutions to Newton’s equations of motion is<br />
€<br />
x n+1 = x n + v n Δt + 1<br />
2 a n Δt<br />
( )2 . (<strong>11.</strong>2)<br />
vn+1 = vn + 1<br />
2 an + a ( n+1)Δt<br />
. (<strong>11.</strong>3)<br />
A subroutine written to carry out N steps of the Verlet algorithm for the harmonic oscillator is given<br />
below. The number of points, time step size, harmonic oscillator force constant, mass, <strong>and</strong> initial<br />
position <strong>and</strong> initial velocity<br />
€<br />
are the variables passed to the subroutine. The subroutine returns two<br />
arrays, the position <strong>and</strong> velocity as functions of time.<br />
SUBROUTINE VERLET(N, DT, K, M, X0, V0, X, V)<br />
IMPLICIT NONE<br />
INTEGER N, I<br />
REAL*8 DT, K, M, X0, V0, A1, A2, X(N), V(N)<br />
X(1) = X0<br />
V(1) = V0<br />
DO 100 I = 2, N<br />
A1 = –K*X(I–1)/M<br />
X(I) = X(I–1) + V(I–1)*DT + 0.5*A1*DT**2<br />
A2 = –K*X(I)/M<br />
V(I) = V(I–1) + 0.5*(A1+A2)*DT<br />
100 CONTINUE<br />
RETURN<br />
END<br />
All the variables passed from the main program to the subroutine as well as any others used<br />
within the subroutine must be defined in the variable declaration statement. As was the case for<br />
external function, the variable names used in the subroutine argument list are dummy variables. The<br />
same names do not have to be used in the main program but their types must match.<br />
The main body of the subroutine carries out multiple iterations of the Verlet equations<br />
(<strong>11.</strong>2) <strong>and</strong> (<strong>11.</strong>3). At the end of the subroutine, the array X contains the position as a function of<br />
time <strong>and</strong> the array V contains the velocity as a function of time. These arrays are passed back to the<br />
main program. The RETURN statement then sends the program control back to the main program.<br />
An example of a main program that calls the VERLET subroutine is given below. The<br />
values of the step size, number of time steps, force constant, mass, <strong>and</strong> initial position <strong>and</strong> velocity<br />
are all input from the screen. The main program then calls the VERLET subroutine to advance the<br />
72