programming and modelling - universiteit utrechtberg/progmod3/progmod3.pdf · programming and...

23
Programming and Modelling Module 3 Fortran Programming (part 3) Applied to Numerical Solution of Differential Equations for Planetary Orbits A.P. van den Berg September 2011 Institute of Earth Sciences Utrecht University 1

Upload: hoangdiep

Post on 03-Apr-2018

238 views

Category:

Documents


12 download

TRANSCRIPT

Page 1: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

Programming and Modelling

Module 3

Fortran Programming (part 3)

Applied to Numerical Solution of

Differential Equations for Planetary Orbits

A.P. van den Berg

September 2011

Institute of Earth SciencesUtrecht University

1

Page 2: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 2

Contents

1 Introduction 3

2 Programming exercises 52.1 Accuracy of numerical differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Accuracy of numerical integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.3 Integrating a single first order differential equation . . . . . . . . . . . . . . . . . . . 72.4 Integrating a single second order equation . . . . . . . . . . . . . . . . . . . . . . . . 9

2.4.1 Escape from a planetary gravity field . . . . . . . . . . . . . . . . . . . . . . . 92.5 Coupled second order equations - planetary orbits . . . . . . . . . . . . . . . . . . . 11

2.5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.5.2 Benchmark calculations for circular orbits . . . . . . . . . . . . . . . . . . . . 132.5.3 Modelling elliptical planetary orbits . . . . . . . . . . . . . . . . . . . . . . . 13

A Numerical differentiation and integration 16A.1 Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16A.2 Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

B Numerical solution of ordinary differential equations 18B.1 Solving first order differential equations . . . . . . . . . . . . . . . . . . . . . . . . . 18B.2 Solving second order differential equations . . . . . . . . . . . . . . . . . . . . . . . . 19

B.2.1 A single second order equation . . . . . . . . . . . . . . . . . . . . . . . . . . 19B.2.2 Coupled second order equations . . . . . . . . . . . . . . . . . . . . . . . . . . 20

B.3 A fourth order Runge-Kutta method . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

C An analytical benchmark for coupled second order ODE’S 23C.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23C.2 Benchmark Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Page 3: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 3

1 Introduction

In this module of the course ‘Programming and Modelling’ the focus is shifted from more tutorialelementary exercises in using elements of the Fortran programming language, (the main topic of thepreceding first two course modules), to application of Fortran programs, written by the students, inmathematical physics experiments.

The subject theme of the experiments in this course module is the numerical solution of ordinarydifferential equations. Mathematical prerequisites are minimal. An elementary understanding of aderivative as a differential quotient and of the integral of a function as the area under the curveof the function will be sufficient. The approach of the subject is mainly pragmatic and for a moremathematical background of the subject, students are referred to specialised courses on differentialequations at the Mathematical Institute, the Physics Faculty or the course on differential equationsfor Earth Science students.

The numerical solution methods for differential equations applied in this course have two mainadvantages. First, they are conceptually simple and therefore easy to implement in a computer codeby non-specialist programmers. Second, these methods are widely applicable in a uniform way, incontrast to analytical methods which are allways restricted to certain special classes of equations.

In the course ‘Programming and Modelling’ the main goal is to teach the students how to developetheir own computer programs, written in the Scilab or Fortran programming languages, besides usingavailable software tools. Application of the student-written programs in simple numerical modellingexperiments is used as a vehicle towards the main goal.

This approach of learning computer programming by application to math and physics modellingproblems represents a revival of an old ideal from the seventies of the last century of obtaining anextremely flexible tool for numerical experiments to supplement the ‘classical’ non-computationalcurriculum. In 1976 Eisberg 1 predicted that the introduction of the programmable pocket calculatorduring the seventies could sufficiently lower the technological threshold for the large scale applicationof numerical modelling in math and physics education to become wide spread. My impression isthat these predictions have, so far, not come through entirely, i.e. not considering more specialisedcurricula like Computational Science.

However, the recent start of the course ‘Programming and Modelling’, combined with the everincreasing availability to students of computing facilities may be another opportunity of realisingthe old ideal also within the Earth Sciences. This time it no longer relies on cumbersome program-ming of pocket calculators. Instead a third generation language, Fortran, is used in an open sourceenvironment, based on the Linux operating system and the GNU gfortran compiler, running on com-paratively powerfull (commodity) PC’s. May be this time we have finally reached the critical mass,technologically, to see the computational approach florish also in computationally non-specializedareas like Earth Science.

In this course module the students perform a series of numerical experiments after implementingnumerical algorithms introduced in the appendices of these course notes. In the first two experi-ments the rate of convergence of alternative numerical schemes for differentiation and integration isinvestigated. This provides the background for the following experiment dealing with the numericalsolution of the first order ordinary differential equation describing natural radioactive decay, usingboth the Euler and (second order) Runge-Kutta methods.

1R.M. Eisberg, Applied mathematical physics with programmable pocket calculators, McGraw-Hill, 1976.

Page 4: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 4

In the next experiment the second order equation describing the 1-D trajectory of an object in acentral gravity field is solved. In the experiments the phenomenon of the critical escape velocity fromthe Earth’s gravity field is investigated. This application of Newtons law a = F/m and his gravitylaw for the magnitude of the gravity force F clearly illustrates the flexible nature of the numericalalgorithms. The non-linear differential equation for the variable gravity field case is solved in thesame way as the linear equation for the case of a uniform gravity field.

In a final experiment the multi-dimensional trajectory of a celestial planetary body orbiting acentral star is investigated. This is done by solving the non-linear coupled second order differentialequations representing Newtons law a = F/m in vector form. As part of this experiment the orbitof planet Mercury, with its relatively high eccentricity, is calculated numerically. The numericaltrajectory coordinates obtained are then used to determine the parameters of a corresponding ellip-tical Kepler orbit, by least squares fitting, and the resulting parameters are verified against availableplanetary data for Mercury.

Page 5: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 5

2 Programming exercises

2.1 Accuracy of numerical differentiation

In Appendix A alternative schemes for numerical differentiation are introduced using a forwarddifference Df end a central difference operator Dc respectively. These numerical schemes can beinvestigated by tabulating the difference approximations for a given function and by investigatingthe difference in the convergence behavior for decreasing difference step values ∆x.

Write a Fortran program to investigate both schemes for a given function f(x). To this endthe function as well as both difference expressions are tabulated for a given interval xmin, xmax andgiven value of ∆x. Tables of f , Dff and Dcf are written to file and plotted with xmgrace. For afixed evaluation point x0 in the interval the error in the difference approximations is computed fora number of values of the difference step ∆x,

Ef =

∣∣∣∣Dff(x)− d

dxf(x)

∣∣∣∣x=x0

, Ec =

∣∣∣∣Dcf(x)− d

dxf(x)

∣∣∣∣x=x0

(1)

Write tables of Ef (∆x) and Ec(∆x) to file for plotting and regression analysis with xmgrace.The function f (derivative of order zero) and its analytical first derivative are implemented in a

Fortran function myfunc, with interface 2 specified in the listing below. The parameter numderiv isused to select the order of the derivative. functype can be used to choose from different implementedfunctions.

The difference operators Df and Dc are implemented in two Fortran functions myfunc_diff1

and myfunc_diff2 for the forward and central difference schemes respectively (see the interfacedefinitions listed below). The Fortran sourcetext file containing the interface definitions listed be-low can be copied from the institute network location: /aw/geof/lib/progmod/progr3/diffquot,together with a Makefile.

These implementations of the difference operators should be set up in a general way, i.e. thenecessary evaluations of f(x) should be done indirectly through function calls to the proceduremyfunc.

Different tables should be written to 2-column ascii text files using a subroutine wr_tab (seethe interface listing below).

module mod_interfaces

interface myfunc

real function myfunc(functype,numderiv,x)

integer functype,numderiv

real x

end function myfunc

end interface myfunc

interface myfunc_diff1

real function myfunc_diff1(functype,x,dx)

integer functype

real x,dx

end function myfunc_diff1

end interface myfunc_diff1

2More information on the use of interface definitions in different applications can be found in, the lecture notesCursus Programmeren (in Dutch). A.P. van den Berg, J. van Hunen and J.H. de Smet, Cursus Programmeren, CourseNotes, Institute of Earth Sciences, Utrecht University, 1999.

Page 6: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 6

interface myfunc_diff2

real function myfunc_diff2(functype,x,dx)

integer functype

real x,dx

end function myfunc_diff2

end interface myfunc_diff2

interface wr_tab

subroutine wr_tab(ndata,x_table,func_table,filename)

integer ndata

real, dimension(*) :: x_table,func_table

character(len=*) filename

end subroutine wr_tab

end interface wr_tab

end module mod_interfaces

Experiments:Investigate the function f(x) = sin(x).

• Produce an overlay plot of both difference approximations, Df and Dc, for a single value of∆x, illustrating the different accuracy of both schemes by plotting the analytical solution forcomparison.

• Also produce an overlay plot of Ef and Ec, with double logarithmic axes and a series of, say,ten ∆x values with ∆xj+1 = ∆xj/2, illustrating the different convergence behavior for bothapproximations.

• Use filled symbols in combination with a plot legend to identify your discrete data points.

• Determine the order of the convergence by a regression analysis. 3 Include the formula of theregression results in the plot legend specification.

• Include this plot figure together with a listing of your program in your report.

2.2 Accuracy of numerical integration

In this experiment you will investigate the accuracy of the numerical evaluation of definite integrals.In a program loop over decreasing integration stepsize values ∆x the integral of a function f(x) iscomputed numerically over an interval [a, b], using both methods described in Appendix A. Theapproximation error of both numerical schemes is determined by comparison with the known ana-lytical result. Write the tables of the approximation errors to 2-column ascii files for plotting withxmgrace.

Implement both numerical integration schemes in different subroutines quad_forward and quad_midp

with interface definitions declared in the module mod_interfaces listed below. The Fortran source-text file containing the interface definitions listed below can be copied from the institute networklocation: /aw/geof/lib/progmod/progr3/quad, together with a Makefile.

The parameter functype is used as a selection parameter for different functions f(x) imple-mented in your program. Both procedures contain calls of the subroutine integ_analyt wherethe necessary integrand values f(xi) are evaluated. The interface of this routine is given in the

3See Appendix D of the coursenotes Programming and modelling, Module 1.

Page 7: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 7

module listed below. This routine also includes the analytical expressions for the integral, used inthe computation of the approximation error. The routine returns either the value of the integrandevaluated in the point x in case itask=1, or the value of the integral over the interval [xmin, xmax]when itask=2.

module mod_interfaces

interface integ_analyt

subroutine integ_analyt(itask,functype,x,xmin,xmax,result)

integer itask, functype

real x,xmin,xmax,result

end subroutine integ_analyt

end interface integ_analyt

interface quad_forward

subroutine quad_forward(functype,xmin,xmax,nx,forw_integral)

integer functype, nx

real xmin,xmax,forw_integral

end subroutine quad_forward

end interface quad_forward

interface quad_midp

subroutine quad_midp(functype,xmin,xmax,nx,midp_integral)

integer functype, nx

real xmin,xmax,dx,midp_integral

end subroutine quad_midp

end interface quad_midp

interface wr_tab

subroutine wr_tab(ndata,x_table,func_table,filename)

integer ndata

real, dimension(*) :: x_table,func_table

character(len=*) filename

end subroutine wr_tab

end interface wr_tab

end module mod_interfaces

Experiments:Investigate the numerical integration of the function f(x) = exp(x), with your program. Produce

an overlay plot of the approximation error against the stepsize ∆x of both approximation schemes,with double logarithmic axes and a series of, say, ten ∆x values with ∆xj+1 = ∆xj/2, illustratingthe different convergence behavior for both approximations. Determine the order of the convergenceby a regression analysis in the same way as in the previous section and compare your results withthe predictions of Appendix A. Include this figure together with a listing of your program in yourreport.

2.3 Integrating a single first order differential equation

In this experiment you will investigate the numerical solution of a first order ordinary differentialequation, dy/dt = −cy, using both the Euler forward method and the RK2 method introducedin Appendix B. In particular you will test the convergence behavior for decreasing values of theintegration step value ∆t. The ODE in Appendix B.1 is used as a test case here.

Write a Fortran program for testing the numerical solution of such an ODE. First write a programfor a single integration of the ODE with a given time step ∆T . Write a table of the numerical sulotion

Page 8: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 8

and the analytical solution to file. Make an xmgrace overlay plot of both solutions and plot theanalytical solution using disconnected (filled) symbols skipping sufficient number of data points suchthat symbols do not overlap.

This program contains two main (nested) loops. The outer loop is over several, say 10, valuesof the fixed integration timestep ∆t. The inner loop is over (constant) integration time steps. Storeboth numerical solutions (euler and RK2) and the analytical solution in allocatable arrays and writetables of these solutions to file. This way the ODE is integrated over the interval [0, tmax], for giveninitial condition y(0) = 1, in each cycle of the outer loop, applying a different integration time stepin each cycle.

The approximation error in the numerical result should be evaluated in the endpoint tmax asthe absolute value of the difference between the numerical solutions and the analytical solution.Produce tables of the approximation error for the different values of the timestep, ∆t, for both theeuler and RK2 method.

For each integration step value the righthand side function of the ODE, f(t, y) = −cy, must beevaluated (twice for the RK2 scheme). Implement this function f in a Fortran function funcrhs,with the following interface defintion,

module mod_interfaces

interface funcrhs

real function funcrhs(c_coeff,y)

implicit none

real c_coeff,y

end function funcrhs

end interface funcrhs

interface wr_tab

subroutine wr_tab(ndata,x_table,func_table,filename)

integer ndata

real, dimension(*) :: x_table,func_table

character(len=*) filename

end subroutine wr_tab

end interface wr_tab

end module mod_interfaces

The Fortran sourcetext file containing the listed interface definitions can be copied from theinstitute network location: /aw/geof/lib/progmod/progr3/ode_scal1.

Note that the righthand side function is taken independent of t in this implementation offuncrhs.

Experiments:

Apply your program to the example in Appendix B with f(t, y) = f(y) = −Cy. Produce anoverlay plot of the approximation error of both integration schemes, with double logarithmic axesand a series of, say, ten ∆x values with ∆xj+1 = ∆xj/2, illustrating the different convergencebehavior for both approximations. Determine the order of the convergence by a regression analysisin the same way as in the previous section. Include this plot figure in your report, together withplots of the numerical solution for contrasting values of ∆t. Also include a listing of your programtexts.

Page 9: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 9

2.4 Integrating a single second order equation

2.4.1 Escape from a planetary gravity field

As an application of the integration of a scalar ODE of order two, discussed in Appendix B, weconsider here the problem of computing the 1-D trajectory y(t) of an object moving without fric-tion in a 1-D variable (radial) gravity field. The governing second order scalar ODE, representingNewtons law a = F/m, is rewritten as a 2-D vector ODE of order one in the dependent variables,y, for the spatial coordinate (height above the planetary surface) and v for the velocity, followingthe procedure in Appendix B.2.1.

The problem of the 1-D trajectory, of an object launched in a uniform gravity field, has beenused as an example application in module one of the programming and modelling course. Here weshall extend this problem by taking into account the decrease of the gravity acceleration above theplanetary surface. The solutions of this non-linear problem show a bifurcation in the dependencefrom the launch velocity at time zero, v0 = v(0). For v0 > vesc the trajectory is ‘unbounded’ and theobject escapes from the planetary gravity field. The escape velocity follows from energy conservationapplied to the sum of kinetic and gravitational potential energy as,

vesc =

√2GM

R(2)

Here R andM are the planet radius and mass respectively andG = 6.6732×10−11 is the gravitationalconstant.

Write a Fortran program that can be used to investigate the escape from the planetary gravity field.In order to validate your program, a numerical solution for the special case of a uniform gravityfield, g0 = GM/R2, must be produced, for comparison with the available analytical solution.

Use the second order RK2 scheme introduced in Appendix B.2.1 to integrate the governing vectorODE. Your program should be set up according to the specifications given below and interfacedefinitions shown in the listing of the module mod_interfaces (see below) should be followed.The Fortran sourcetext file containing the interface definitions listed below can be copied from theinstitute network location: /aw/geof/lib/progmod/progr3/escape, together with a Makefile.

module mod_interfaces

interface fungravity

real function fungravity(y)

real y

end function fungravity

end interface fungravity

interface sol_analyt

subroutine sol_analyt(surface_gravity,y_initial,v_initial, &

time,ycoord,velocity)

real surface_gravity,y_initial,v_initial,time,ycoord,velocity

end subroutine sol_analyt

end interface sol_analyt

interface vecrhsfunc

subroutine vecrhsfunc(y,v,vec1_out,vec2_out)

real y,v,vec1_out,vec2_out

end subroutine vecrhsfunc

end interface vecrhsfunc

interface wr_tab

Page 10: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 10

subroutine wr_tab(ndata,x_table,func_table,filename)

integer ndata

real, dimension(*) :: x_table,func_table

character(len=*) filename

end subroutine wr_tab

end interface wr_tab

end module mod_interfaces

• In order to make your program applicable to different planets and moons, the parametersdefining the radial gravity field, total planetary mass and radius, should be read from inputfile and defined as variables located in a Fortran module, mod_planetparameters, that shouldbe applied with a use statement in the program units where these parameters must be defined.

• Use a program option parameter, itype_gravity, declared in mod_planetparameters, tochoose between model cases with uniform gravity, itype_gravity = 1, and variable gravity,itype_gravity = 2. This parameter is used in your function fungravity, specified below.

• Define the discretization of the integration time interval from the following parameters readfrom the standard input file, t_max, ntimes. Where [0,t_max] is the integration timewindow and ntimes is the number of integration times, including the initial time. Truncate thecomputation of the trajectory at the time step before impact in case of a ‘bounded trajectory’.

• Use a Fortran subroutine vecrhsfunc for the calculation of the righthand side vector func-tion according to the procedure in Appendix B.2.1. See mod_interfaces for the interfacedescription of this subroutine.

• Use a Fortran function fungravity for the calculation of the local value of the gravity accel-eration as a function of the coordinate y. See mod_interfaces for the interface descriptionof this function. This function is called from the subroutine for the right hand side functionvecrhsfunc.Note: by setting the gravity acceleration in fungravity equal to a uniform value correspond-ing to the value at the planetary surface, you can check your implementation of the numericalintegration scheme of the governing ODE against the available analytical solution. To this endlocate the variable surface_gravity, computed from the input parameters in the programmodule mod_planetparameters.

Implement uniform gravity as a special case in your function fungravity, using the modelswitch itype_gravity defined in the previous items.

• Use a Fortran function sol_analyt that computes the coordinate and velocity for the specialcase of the uniform gravity acceleration g0 defined by the value of the radial gravity valueat the planetary surface, represented by the program variable surface_gravity from theprevious item. Use the interface of this routine, defined in mod_interfaces.

• Use a Fortran subroutine wr_tab to write tables of your time-series results to several two-column ascii output files ready for plotting with xmgrace. Use the interface of this routinedefined in mod_interfaces.

Experiments

Page 11: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 11

1. Compute trajectories for different initial velocities respectively smaller and greater than theescape velocity from the Earth’s surface. Present your result in a single figure containing twocolumns (for two contrasting launch velocities) of three frames each. The top frame showsthe y coordinate versus time, the second one the velocity v and the bottom frame the gravityacceleration at the position of the object versus time.

2. To validate your program produce modelling results for a uniform gravity case both numericallyand analytically. Plot the curves of the numerical results as solid lines and plot the analyticalresults as discrete symbols of a contrasting color. Display a reduced set of analytical datapointssuch that the discrete symbols do not overlap.

2.5 Coupled second order equations - planetary orbits

2.5.1 Introduction

The previous section dealt with the escape from the gravity field of a planet and the problem washandled in one-dimension. Here we consider the multi-dimensional problem of orbit calculations ina central gravity field. The orbit of a planet in the gravity field of its central star is described by a(vector) ordinary differential equation of second order, introduced in Appendix B.2.2.

In the appendix a numerical solution is developed for the governing vector ODE for 2-D planetarytrajectories (x(t), y(t)).

Write a Fortran program traject2d that can be applied to compute the trajectory of a celestialbody in a central gravity field, applying the one-body approximation introduced in the Appendix.Use the RK2 scheme for 2-D problems introduced in Appendix B.2.2 to integrate the governingODE.

Your program should be set up according to the specifications given below:

• Use the interface definitions in the module mod_interfaces printed below.

module mod_interfaces

interface fungravity2d

function fungravity2d(x,y)

use mod_real_kind

real(kind=real_kind) fungravity2d,x,y

end function fungravity2d

end interface fungravity2d

interface vecrhsfunc2d

subroutine vecrhsfunc2d(x,v,y,w,v1out,v2out,v3out,v4out)

use mod_real_kind

real(kind=real_kind) x,v,y,w,v1out,v2out,v3out,v4out

end subroutine vecrhsfunc2d

end interface vecrhsfunc2d

interface wr_tab

subroutine wr_tab(ndata,x_table,func_table,filename)

use mod_real_kind

integer ndata

real(kind=real_kind), dimension(*) :: x_table,func_table

character(len=*) filename

end subroutine wr_tab

end interface wr_tab

end module mod_interfaces

Page 12: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 12

• Note that real variables in the above interfaces have an extra (kind) parameter in theretype declaration. This way different levels of machine precision, 4-byte (32 bit), the default,or 8-byte (64 bits) can be used. The machine precision determines the round-off error incalculations. 4 In the implementation used here the value of the kind parameter is set forsingle precision in module mod_real_kind, listed below.

module mod_real_kind

integer, parameter :: real_kind=4 ! single precision real (4 bytes)

end module mod_real_kind

• Use the make utility to install your program. The necessary Makefile and the source files ofthe Fortran modules can be copied from the network directory,/aw/geof/lib/progmod/progr3/traject2d.

• For applications in our solar system a number of parameters can be set fixed in your program.Define a number of physical constants as parameter variables located in a Fortran modulemod_physparameters, listed below.

module mod_physparameters

use mod_real_kind

real(kind=real_kind), parameter :: gravity_constant = 6.6732e-11

real(kind=real_kind), parameter :: solar_mass = 1.989e30

real(kind=real_kind), parameter :: astro_unit = 1.496e11

real(kind=real_kind), parameter :: timescal_year = 365*24*3600

real(kind=real_kind), parameter :: c_coef = &

gravity_constant*solar_mass * timescal_year **2/(astro_unit**3)

end module mod_physparameters

• Use a righthand side (vector) function vecrhsfunc2d for the RK2 integration scheme with aninterface definition specified in the module mod_interfaces listed above.

• Use a function fungravity2d for the computation of the magnitude of the gravity accelerationalong the 2-D trajectory, with an interface specified in the module mod_interfaces listedabove. Note this scalar quantity is used only for visualization of the results. The computationof the vector components of the gravity force field can be implemented directly in the righthandside function vecrhsfunc2d.

• Your program computes tables of cartesian coordinates x(t), y(t), of the x and y components ofthe instantaneous velocity v(t), w(t) and the velocity amplitude

√v2 + w2 for a single celestial

body, for given initial conditions x(0), y(0) and v(0), w(0).

• The tables in the previous item are written to 2-column ascii text files, ready for plotting withxmgrace.

• Write all input parameters of your program with corresponding text labels to a log file andinclude this file in your report.

4See the (Dutch) coursenotes Cursus Programmeren, Appendix B.2.3.

Page 13: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 13

2.5.2 Benchmark calculations for circular orbits

Test your program in a benchmark computation for the case of a circular planetary orbit where asimple analytical solution is available, described in Appendix C. Investigate the convergence of theEuler and RK2 schemes by doing full orbit calculations for a range of fixed integration time step.Produce a graph of the relative error in a single orbit versus the integration time step using doublelogarithmic axes. Used filled symbols in combination with a plot legend to identify the diferrentresults. Determine the convergence rate by fitting a powerlaw relation with xmgrace. Include thefit results in the plot legend.

The convergence rate for the Euler and RK2 schemes should be one and two respectively. Thisbenchmark is used as a validation for the correct implementation of the integration schemes for theODE’s and as an assessment of timestep requirements for given accuracy specifiation.

Investigate the role of the machine precision used in your calculations, specified in modulemod_real_kind. First do the convergence tests using single precision with the parameter real_kind=4.

Then repeat the calculations using double precision arithmetic with parameter real_kind=8.

Use physical parameters, representative for the solar system that are located in a Fortran modulemod physparameters and listed in Table 1, together with the specification of the initial conditionsand orbit time of the resulting circular orbit.

Hint: To obtain these results the full circle orbit time τ0 and (initial) velocity values listed inTable 1 should be computed first in your program using the expresions in Appendix C. The totalintegration time is then set to τ0 and the constant integration time step ∆t is defined from thenumber of time steps specified in the program input.

symbol V alue Units

G Gravity constant 6.6732 · 10−11 Nm2kg−2

M Solar mass 1.989 · 1030 kgr0 Astronomical Unit 1.496 · 1011 mt0 Time scale (1 year) 365 · 24 · 3600 = 3.1536 · 107 s

C =GMt20

l30Scaling coefficient 39.42643 -

(x(0), y(0)) init.coord. (1, 0) -(v(0), w(0) init.velocity (0, 6.279047) -

τ0 period circ.orbit 1.000659 -

Table 1: Model parameters used in the circular orbit benchmark computations. The velocity compo-nent w(0) is computed using (53). The period of the circular benchmark orbit τ0 has been computedusing (50).

2.5.3 Modelling elliptical planetary orbits

Next apply your program to an orbit calculation for an elliptic planetary orbit with non-zero orbiteccenttricity e listed for several planets in Table 2.

1. Test your program by computing the orbits for Earth and Mercury which have contrastingeccentricity values, listed in Table 2. Determine the orbital parameters (Kepler elements), thesemimajor axis a and the eccentricity e, from the computed trajectory of the celestial body.

Page 14: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 14

Planetary parameters

Planet a [AU ] e

Mercury 0.38709880 0.20563175Venus 0.72333201 0.00677177Earth 1.00000083 0.016708617Mars 1.52368946 0.09340062

Table 2: Parameters from: C.F. Yoder, 1995. Astronomical and geodetic properties of Earthand the solar system, in: Global Earth Physics, A Handbook of Physical Constants, AGUReference Shelf 1, American Geophysical Union.

Define initial conditions for the position where the orbiting object is closest to the Sun, the‘periapse’. Here the velocity vector is perpendicular to the line connecting the object and theSun. Compute the distance from the Sun in the periapse from the known parameters of theelliptical orbit, the length of the semimajor axis a and the eccentricity e, listed in Table 1,expressed in ‘astronomical units’ (1.496× 1011m). The Sun is located in the focal point of theellips closest to the periapse. The distance from the Sun to the central symmetry point of theellips equals ea and the distance between Sun and periapse is (1− e)a.

For the initial value of the velocity, choose the x-axis along the semimajor axis and set v(0) = 0.The y-component of the initial velocity w(0), can be computed from an expression for theconstant orbtital energy (de Pater and Lissauer, 2001)

E = Ek + Ug =1

2mv2 − GMm

r= −GMm

2a(3)

Substitution of r = (1− e)a for initial position in the periapse it follows that,

w2(0) =GM

a

(1 + e

1− e

)(4)

Define polar coordinates (r, θ) with the origin in the focal point occupied by the star and θ = 0in the periapse on the major axis. An elliptical orbit can then be parameterized as,

r(t) =a(1− e2)

1 + e cos(θ)=r(0)(1 + e)

1 + e cos(θ)(5)

where the initial value of the solar distance in the periapse, r(0) = (1−e)a has been substituted.

The orbital elements can then be determined by least squares fitting from the numerically com-puted orbital coordinates, tabulated as (cos(θ), 1/r). This can be done by a linear regression ofthe tabulated numerical results using xmgrace. Use menu buttons: Data > Transformations

> Regression and choose the default Linear option. Include a (cos(θ), 1/r) plot showingdiscrete points from your numerical calculation together with the linear regression line deter-mined by xmgrace. Include the formula of the regression result in the plot legend specification.

Note: This experiment is in the spirit of the original least squares analysis by C.F. Gauss ofa limited number of positions of asteroid number one, Ceres, determined by Piazzi in 1801.

Page 15: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 15

From this analysis Gauss could predict the position of Ceres which provided the basis of therediscovery of Ceres several months later. 5

2. Verify that an unbound trajectory is obtained when the orbital energy is defined positive, bychoosing a sufficiently large initial velocity, E = Ek + Ug > 0.

5http://scienceworld.wolfram.com/biography/Gauss.html

Page 16: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 16

Appendix

A Numerical differentiation and integration

A.1 Differentiation

The first derivative of a function f(x) can be approximated by difference approximations related tothe defining differential quotient,

d

dxf(x) = lim

∆x→0

f(x+ ∆x)− f(x)

∆x(6)

From this we define (for finite values of ∆x), the forward difference operator,

Dff(x) =f(x+ ∆x)− f(x)

∆x(7)

Problem: Derive an error estimate Ef for the difference approximation (7) by means of a Taylor series expansion of f(x+ ∆x)in the evaluation point x.Answer:

Ef =

∣∣∣Dff(x)−d

dxf(x)

∣∣∣ = O(∆x) (8)

A related, more accurate approximation is defined by the central difference operator,

Dcf(x) =f(x+ ∆x

2 )− f(x− ∆x2 )

∆x(9)

Problem: Derive an error estimate Ec for the difference approximation (9) by means of a Taylor series expansion of f(x+ ∆x2

)

and f(x− ∆x2

) in the evaluation point x.Answer:

Ec =

∣∣∣Dcf(x)−d

dxf(x)

∣∣∣ = O(∆x2) (10)

A.2 Integration

The definite integral of a function f(x) on an interval [a, b] can be approximated numerically indifferent ways. In the numerical schemes for the solution of ordinary differential equations introducedin Appendix B, alternative approximations are applied to definite integrals leading to differentintegration methods for ODE’s.

A straightforward approximation is obtained by splitting the integral in a sum over approximatecontributions from n subintervals spanned by n+ 1, function evaluation points xi,∫ b

af(x)dx ≈

n∑i=1

f(xi)∆x (11)

where x1 = a, xi = a + (i − 1)∆x, xn = b − ∆x and ∆x = (b − a)/n. In (11) the integrand fis approximated on each subinterval by forward extrapolation. Note that the function value of theendpoint f(xn+1) is not used in this approximation.

Page 17: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 17

Problem: The error in this forward integration scheme appears to be of first order in the stepsize ∆x. In order to show this,expand the integrand function in each of the subintervals in a Taylor series truncated after the first order term. Integrate thisexpansion and derive the following estimate for the approximation error,

E <1

2∆x(b− a)M (12)

where M is an upperbound of the first derivative |f ′(x)| < M, a ≤ x ≤ b.

A more accurate approximation of the integral is obtained by using a midpoint approximationon the same subintervals instead of a forward extrapolation. This implies a choice in (11) withx1 = a+ ∆x/2, xi = a+ (i− 1/2)∆x, xn = b−∆x/2.

It can be shown in a similar way as in the above problem that the approximation error in thismidpoint scheme is of second order in ∆x. This is the reason why midpoint schemes involved inthe integration of ordinary differential equations have a higher order accuracy then correspondingschemes based on forward extrapolation.

Page 18: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 18

B Numerical solution of ordinary differential equations

B.1 Solving first order differential equations

The basic form of the ordinary differential equations (ODE’s) used in this course module is,

dy

dt= f(t, y) (13)

This is a first order ODE in the unknown function y(t) where t is the independent variable. Wewill discuss in particular the initial value problem where solutions of (13) are constructed for giveninitial value y(0) = y0.

An example of this general form is the equation describing natural radioactive decay of unstableisotopes.

dy

dt= −Cy (14)

where y(t) represents the time dependent concentration of a decaying isotope and C is the decayconstant. For given initial concentration y(0) = y0, this equation has a well known solution,

y(t) = y0 exp(−Ct) (15)

Equation (14) can be used as a benchmark case for illustration and testing more generallyapplicable numerical solution schemes for ODE’s.

With numerical solution schemes for ODE’s we compute approximate values of the unknownfunction for a set of discrete time values, t0, t1, . . . , tn. The corresponding values of the numericalsolution are denoted by subscripts y(ti) = yi. The time increment ∆ti = ti+1 − ti can be madevariable in adaptive schemes. In such cases the timestep is chosen to depend on the rate of changeof the solution.

A general scheme for solving ODE’s of the form (13) follows from integrating the equation over asingle time step.∫ ti+∆t

ti

dy

dt′dt′ = y(ti + ∆t)− y(ti) = yi+1 − yi =

∫ ti+∆t

ti

f(t′, y)dt′ (16)

Different methods can now be derived by using alternative approximations for the integrand in therighthand side of (16), as described in Appendix A. A conceptually simple scheme is obtained if weapproximate the integrand function by means of forward (uniform) extrapolation from the ‘initialvalue’ for t = ti

yi+1 = yi + ∆tf(ti, yi) (17)

This integration scheme is known as the forward Euler method. It can be shown that, for ‘wellbehaving’ functions f , this scheme has a first order convergence behavior for decreasing ∆t, i.e. thedifference between the numerical solution and the analytical solution is of order ∆t.

Problem: Verify the relation between the forward Euler method and the numerical methods of integration described in Appendix

A.

Page 19: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 19

The accuracy can be improved if we use a mid-point approximation for the integrand in (16). Tothis end we first extrapolate y from ti to ti+1/2 = ti + ∆t/2, using a half-step forward extrapolationand substitute the resulting value, yi+1/2, in the righthand side function f . The result becomes,

yi+1 = yi + ∆tf(ti +∆t

2, yi+1/2) (18)

where the mid-point value of y is approximated by linear extrapolation as,

yi+1/2 = yi +∆t

2f(ti, yi) (19)

This method is known as a second order Runge-Kutta (RK2) method. It can be shown that itconverges as ∆t2.

B.2 Solving second order differential equations

B.2.1 A single second order equation

Often the differential equation to be solved is not given as a first order equation. In such cases asingle equation of order m can be rewritten as a set of m equations of order one by introducing newdependent variables,

y1(t) = y(t), yj(t) =dyj−1

dt, j = 2, . . . ,m (20)

where the function index j is not to be confused with a time index. This is illustrated for the mostcommon case of the second order equation,

d2y

dt2= f(t, y,

dy

dt) (21)

By introducing the new dependent variable, v(t) = dydt , we get a set of two first order equations,(

dydtdvdt

)=

d

dt

(y(t)v(t)

)=

(v(t)

f(t, y, v)

)(22)

Now a similar integration as in (16) can be applied to obtain different numerical solution schemes,∫ ti+∆t

ti

d

dt′

(y(t′)v(t′)

)dt′ =

(yi+1

vi+1

)−(yivi

)=

∫ ti+∆t

ti

(v(t′)

f(t′, y, v)

)dt′ (23)

Forward extrapolation of the integrand vector in (23) results in the following Euler forward vectorscheme,(

yi+1

vi+1

)=

(yivi

)+ ∆t

(vi

f(ti, yi, vi)

)(24)

In a similar way as in the previous section an improved method can be obtained by using a midpointapproximation to the integral in (23),(

yi+1

vi+1

)=

(yivi

)+ ∆t

(vi+1/2

f(ti+1/2, yi+1/2, vi+1/2)

)(25)

Page 20: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 20

where the midpoint vector is computed using forward extrapolation over a half time step,(vi+1/2

f(ti+1/2, yi+1/2, vi+1/2)

)=

(vi + ∆t

2 f(ti, yi, vi)

f(ti+1/2, yi + ∆t2 vi, vi + ∆t

2 f(ti, yi, vi))

)(26)

An example of a second order equation that can be solved using either one of the above schemes(24) or (25) is the equation for the 1-D trajectory y(t) of an object moving without friction in avertical gravity field,

d2y

dt2= −g (27)

where the vertical coordinate increases in the upward direction and the gravity force per unit mass−g is oriented in the downward direction. Assuming further that the gravity field depends only onthe spatial coordinate and not explicitly on the time coordinate, we have f(t, y, v) = f(y) = −g(y)and the second order scalar ODE can be reformulated as a first order vector ODE,

d

dt

(y(t)v(t)

)=

(v(t)−g(t)

)(28)

Applying the algorithms for the Euler forward (24) and RK2 schemes (25), respectively to 28, weget the following alternative solution schemes,(

yi+1

vi+1

)=

(yivi

)+ ∆t

(vi−gi

)(29)

(yi+1

vi+1

)=

(yivi

)+ ∆t

(vi − ∆t

2 gi−gi+1/2

)(30)

where gi = g(yi) and gi+1/2 = g(yi+1/2), with yi+1/2 = yi + vi∆t/2.

B.2.2 Coupled second order equations

The mechanical example in B.2.1 deals with a 1-D trajectory of an object described by a singlesecond order differential equation representing Newtons second law F = m × a. For a 2-D or 3-Dtrajectory, Newtons law would result in two or three such second order ODE’s respectively, one foreach trajectory coordinate involved. Here we shall only investigate the 2-D case. Extension to thefull 3-D case is then straightforward. The 2-D equations can be applied to solve Newtons equationfor planets orbiting a star. The problem of a single planet orbiting a star is known as the two-bodyproblem, where both objects orbit their common center of mass xc, with dxc/dt = 0 in the absenceof external gravity forces. This problem can be reformulated as a one-body problem, with the originof the coordinate system in the center of mass. For a system like the Sun/Earth with a mass ratioof order 106 this is, to a good approximation, the same as considering the orbit of the planet arounda fixed central star. 6

Note: the small deviation of this approximation from the exact solution, resulting in a low amplitude‘wobbling’ of the central star due to the orbiting planet, is the basis of the discovery of most of theknown exoplanets in recent years, by (Doppler) spectral analysis of the light from the central star.

6I. de Pater and J. Lissauer, Planetary Sciences, Cambridge University Press, 2001.

Page 21: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 21

The two second order equations for the 2-D case are,

d2x

dt2=Fx

m,d2y

dt2=Fy

m(31)

Here Fx and Fy are the x and y components of the total gravity force acting on the planet. Thisgravity force is given by Newtons law of gravitation

F(x, y) = −GMm

r2er (32)

where r is the radial coordinate with respect to the origin taken in the center of the Sun. G is thegravitational constant, G = 6.6732×10−11Nm2kg−2, M = 1.98×1030kg is the mass of the Sun andm = 5.97× 1024 kg is the mass of the Earth. er = (cos(θ), sin(θ)) = (x/r, y/r) is the unit vector inthe radial direction, θ the polar coordinate measuring the angle between the planets instantaneousposition and the x coordinate axis, which is kept fixed with respect to the stars. Substitution in(31) we obtain,

d2x

dt2= −GMx

r3,d2y

dt2= −GMy

r3(33)

In order to be able work with values of variables with an order of magnitude one, we switch to non-dimensional variables, denoted by primes, defined by choosing suitable scale parameters. For thelenght scale we choose the mean distance between Earth and the Sun l0, the ‘astronomical unit’ (AU),l0 = 1.496× 1011m. For the time scale we apply the length of an Earth year t0 = 365× 24× 3600 =3.1536 × 107 sec. For the mass scale we take the solar mass M0 = M . Substitution of the scalevalues in,

x = l0x′, y = l0y

′, t = t0t′ (34)

we get,

d2x′

dt′2= −C x′

r′3,d2y′

dt′2= −C y′

r′3(35)

where the non-dimensional prefactor C is defined as,

C =GM0t

20

l30(36)

Substitution of the scale values in (36) gives C = 40.47. In the following we drop the primes in thenotation of the non-dimensional variables.

The two second order equations (35) (with primes dropped) are rewritten into a system of four firstorder equations by substitution of the velocity component variables, v = dx/dt and w = dy/dt andthe righthand side vector function elements,

Fx = −C x

r3, Fy = −C y

r3(37)

d

dt

x(t)v(t)y(t)w(t)

=

v(t)

Fx(x, y)w(t)

Fy(x, y)

(38)

Page 22: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 22

This first order vector ODE can be integrated with the Euler forward method as before,xi+1

vi+1

yi+1

wi+1

=

xiviyiwi

+ ∆t

vi

Fx(xi, yi)wi

Fy(xi, yi)

(39)

or with the more accurate RK2 method,xi+1

vi+1

yi+1

wi+1

=

xiviyiwi

+ ∆t

vi+1/2

Fx(xi+1/2, yi+1/2)

wi+1/2

Fy(xi+1/2, yi+1/2)

(40)

where the last midpoint vector is computed by a half step extrapolation,vi+1/2

Fx(xi+1/2, yi+1/2)

wi+1/2

Fy(xi+1/2, yi+1/2)

=

vi + ∆t

2 Fx(xi, yi)

Fx(xi + ∆t2 vi, yi + ∆t

2 wi)

wi + ∆t2 Fy(xi, yi)

Fy(xi + ∆t2 vi, yi + ∆t

2 wi)

(41)

B.3 A fourth order Runge-Kutta method

Besides the second order accurate RK2 method there is also a, fourth order accurate, Runge-Kuttaintegration method labeled RK4. 7 For the following vector ODE,

d

dty = f(t,y) (42)

the second and fourth order Runge-Kutta algorithms, RK2 and RK4, can be specified in termsof evaluations of the righthand side vector function f . This can be done in a straightforwardgeneralization of the algorithm for scalar ODE. 8

To this end define the vectors ki, i = 1, . . . , 4,

k1 = ∆t f (ti,yi) (43)

k2 = ∆t f(ti+1/2,yi+1/2

)= ∆t f

(ti +

1

2∆t,yi +

1

2k1

)(44)

k3 = ∆t f

(ti+1/2,yi +

1

2k2

)(45)

k4 = ∆t f

(ti+1,yi +

1

2k3

)(46)

The RK2 algorithm is specified as,

yi+1 = yi + k2 (47)

The RK4 algorithm is specified as,

yi+1 = yi +1

6k1 +

1

3k2 +

1

3k3 +

1

6k4 (48)

7http://en.wikipedia.org/wiki/Runge-Kutta methods8Press et al., Numerical Recipes

Page 23: Programming and Modelling - Universiteit Utrechtberg/progmod3/Progmod3.pdf · Programming and Modelling Module 3 Fortran Programming ... to application of Fortran programs, written

11/09 23

C An analytical benchmark for coupled second order ODE’S

C.1 Introduction

The coupled equations for the orbit coordinates are,

d2x

dt2= −GM

r3x ,

d2y

dt2= −GM

r3y (49)

with r =√x2 + y2. For the special case of a circular orbit we have r = r0 = constant. Substitution

shows that the equations (49) decouple into two linear ODE’s with constant coefficients and simpleharmonic solutions.

d2x

dt2= −GM

r30

x = −ω20x , ω0 =

√GM

r30

=2π

τ0, τ0 = 2π

√r3

0

GM, s = ω0r0 =

√GM

r0(50)

where ω0, τ0 and s are the angular frequency and corresponding period of the circular motion ands is the magnitude of the velocity. With general solutions x(t) = c1 cos(ω0t + c2). The integrationconstants follow from the initial conditions: (1) x(0) = c1 cos(c2) and (2) dx/dt|t=0 = −c1ω0 sin(ω0t+c2)|t=0 = 0→ c2 = 0 and c1 = x(0) = r0.

For the perpendicular coordinate we have in a similar way, y(t) = d1 sin(ω0t+d2) and the initialconditions give, (1) y(0) = 0 → d2 = 0 and (2) dy/dt|t=0 = w(0) = v0 = d1ω0 cos(0) = d1 → d1 =v0/ω0.

For the magnitude of the velocity vector we obtain, |v|2 = v2 + w2, with x = r0 cos(ω0t), v =−r0ω0 sin(ω0t) and y = r0 sin(ω0t), w = r0ω0 cos(ω0t), we have |v| =

√v2 + w2 = ω0r0 a constant

velocity.The initial condition for the y-component of the velocity follows from this: with,

v(0) = 0, w(0) = |v| = ω0r0 =

√GM

r0(51)

C.2 Benchmark Specification

The formula given above define an analytical reference solution for a benchmark calculation with acircular orbit and constant velocity amplitude. Consider Earth-like parameters and scaling param-eters as defined in the course notes (B.2.2). Then the initial conditions for the orbit calculation canbe set as,

(x(0), y(0)) = (r0, 0) (52)

(v(0), w(0)) =

(0,

√GM

r0

)(53)

This way a full orbit can be modelled and an approximation error is computed from the mismatchof the analytical and numerical orbit defined as the distance between the start and end points ofthe orbit calculation.