Numerical Analysis Using R Solutions To
Numerical Analysis Using R Solutions To
This book presents the latest numerical solutions to initial value problems and
boundary value problems described by ODEs and PDEs. The author offers
practical methods that can be adapted to solve wide ranges of problems and
illustrates them in the increasingly popular open source computer language R,
allowing integration with more statistically based methods.
The book begins with standard techniques, followed by an overview of
“high-resolution” flux limiters and WENO to solve problems with solutions
exhibiting high-gradient phenomena. Meshless methods using radial basis
functions are then discussed in the context of scattered data interpolation and
the solution of PDEs on irregular grids. Three detailed case studies demon-
strate how numerical methods can be used to tackle very different complex
problems.
With its focus on practical solutions to real-world problems, this book is
useful to students and practitioners in all areas of science and engineering,
especially those using R. R Code is available for download from the book’s
home page.
NUMERICAL
ANALYSIS USING R
Solutions to ODEs and PDEs
Graham W. Griffiths
City University, United Kingdom
www.cambridge.org
Information on this title: www.cambridge.org/9781107115613
© Graham W. Griffiths 2016
This publication is in copyright. Subject to statutory exception
and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2016
Printed in the United States of America
A catalog record for this publication is available from the British Library.
Library of Congress Cataloging in Publication Data
Names: Griffiths, Graham W.
Title: Numerical analysis using R : solutions to ODEs and PDEs / Graham W. Griffiths,
City University, United Kingdom.
Description: New York, NY : Cambridge University Press, 2016. | Includes bibliographical
references and index.
Identifiers: LCCN 2015046150 | ISBN 9781107115613 (hardback : alk. paper)
Subjects: LCSH: Initial value problems – Data processing. | Boundary value problems –
Data processing. | Differential equations – Data processing. | Differential equations,
Partial – Data processing. | Numerical analysis. | R (Computer program language)
Classification: LCC QA378 .G76 2016 | DDC 518.0285/5133–dc23
LC record available at http://lccn.loc.gov/2015046150
ISBN 978-1-107-11561-3 Hardback
Cambridge University Press has no responsibility for the persistence or accuracy of URLs
for external or third-party Internet Web sites referred to in this publication and does not
guarantee that any content on such Web sites is, or will remain, accurate or appropriate.
Contents
Preface page xv
vii
viii Contents
Contents ix
x Contents
Contents xi
xii Contents
Contents xiii
Preface
xv
xvi Preface
R language. Both are highly recommended. The R language can be downloaded from
http://cran.r-project.org/. To supplement the R installation, a free interactive develop-
ment environment (IDE), RStudio, can be downloaded from https://www.rstudio.com/.
RStudio provides a very user-friendly customizable user interface that greatly enhances
programming productivity and graphical display of simulation results. For users famil-
iar with Matlab, a comprehensive cross-reference between Matlab and R commands has
been compiled by Dr. David Hiebeler of the University of Maine and can be downloaded
from http://www.math.umaine.edu/~hiebeler.
We emphasize two areas of style usage that have been adopted in this book. The first
is that the symbol used for assignment is <- (also known as the gets symbol), which is the
R purist’s form. However, it is acknowledged that = is used extensively in the R literature
and that choosing between <- and = could be considered simply a matter of semantics,
as there are only a few special situations in which = does not work properly. The second
area of style usage relates to global variables, that is, those variables created outside of a
function but that can be used inside a function. Global variables created using the super-
assignment symbol <<- can also be changed within a lower environment function using
<<-. This means that, in general, they are allocated higher in the environment hierarchy
than where they are used. Now, like all modern programming languages, variables in R
are passed to functions by reference, but global variables are allowed. In this book, we
tend to make great use of global variables, as such use leads to cleaner and less cluttered
code. It also avoids having to process lists returned from functions where, in the rare situa-
tion, globals are actually changed within a function rather than just used. However, we do
not use global variables wherever possible and pass values through function arguments
where it is appropriate or where it makes the code clearer. For applications described in
this book, the scope for global variables is generally between adjacent levels in the envi-
ronment hierarchy and therefore is not readily prone to programming conflicts. A good
discussion relating to the use of global variables can be found in [Mat-11, chap. 7].
OVERVIEW OF CONTENTS
Chapter 1 introduces the subject of ordinary differential equations, and basic integration
methods are covered, including Euler, Runge–Kutta, variable step, extrapolation, BDFs,
NDFs, and Adams. The Newton and Levenberg–Marquardt convergence methods are
introduced in connection with implicit integration. A discussion relating to truncation
error and verification of integration order is presented with a number of examples that
use the concepts discussed. The chapter concludes with a brief discussion on stiffness.
Chapter 2 explores some of the theory and practical applications of ODE integrator
stability analysis. The discussion includes topics on global order of accuracy, A-stable
and zero-stable definitions, and the Dahlquist barrier theorems. Using the Dahlquist test
problem, we investigate the stability of various integration methods, including Runge–
Kutta, variable step, BDFs, NDFs, and Adams. For each method, the stability regions are
plotted in the complex plane to illustrate the associated stability margins.
Chapter 3 discusses Cauchy problems in the context of initial value and/or bound-
ary value problems. The basic concepts relating to PDEs and their classification are dis-
cussed, along with initial conditions (ICs) and the various types of boundary conditions
(BCs). General ideas relating to discretization methods, mesh grid, stencils, upwinding,
Preface xvii
and the Courant–Friedrichs–Lewy number are introduced. This leads into a discussion
on the method of lines (MOL), one of the major numerical schemes for solving PDEs.
A good selection of 1D and 2D example MOL problems are solved. These examples,
in both Cartesian and polar coordinates, have been chosen to bring out the main ideas
and to show the variety of problems that can be solved using this method. Then follows
a brief discussion of the following fully discrete methods: FTBS, implicit FTBS, FTCS,
implicit BTCS, leapfrog, Beam–Warming, Lax–Friedrichs, and Lax–Wendroff. Solutions
are compared for the different methods applied to sample problems. The ideas behind
the finite volume method are presented in preparation for their use in high-resolution
schemes, which are discussed subsequently in Chapter 6.
Chapter 4 discusses the concept of a system being well-posed and ways of using this
idea to investigate system stability. The matrix stability method is outlined, and detailed
stability calculations are included for semi-discrete PDE schemes. A number of exam-
ples are included that analyze PDEs, and results are presented in graphical form. The
von Neumann stability method is discussed with the fundamental ideas developed using
Fourier transforms. Various semi-discrete and fully discrete PDE systems are analyzed,
with results presented graphically.
Chapter 5 introduces the idea of the dispersion relation and its relationship to wave
number and wave frequency. The accuracy of numerical schemes is discussed in relation
to numerical amplification and exact amplification factors. Also discussed is how these
factors can be used to provide an indication of phase (dispersion) and amplitude (dissi-
pation) errors. The chapter concludes with a discussion on phase and group velocities.
Chapter 6 introduces the idea of high-resolution schemes for the solution of PDEs.
The Riemann problem is discussed, along with Godunov’s method of providing an
approximate solution. A discussion follows on the principle of total variation dimin-
ishing (TVD) and how Godunov’s order barrier theorem places constraints on mono-
tonic PDE solution methods. An introduction is then provided to two major methods
that are employed widely to solve these types of problems. The first is the flux lim-
iter method, whereby fifteen different flux limiter functions are presented. The second
is the weighted essentially nonoscilliatory (WENO) method, whereby the associated
weights and smoothness indicator calculations are presented. These methods are dis-
cussed within a finite volume and MOL framework. They are based on the monotone
upstream-centered schemes for conservation laws (MUSCL) method, with the particu-
lar implementation being the Kurganov and Tadmor central scheme. A variety of 1D and
2D problems are solved using these methods, and the results are presented graphically.
These include, advection, Burgers, Buckley–Everett, Euler equations, Sod’s shock tube,
Taylor–Sedov detonation, Woodward–Colella interacting blast wave, and frontogenesis:
all computationally demanding PDE evolution problems.
Chapter 7 introduces the concept of meshless methods using radial basis functions
(RBFs). These methods represent important tools for the numerical analyst and are
becoming very popular for solving otherwise difficult problems. One of the main advan-
tages of meshless methods is that they can be used on irregular grids and therefore
are applicable to problem geometries of any shape. The ideas are presented from an
introductory-basics level, with examples showing how the method is used to interpolate
scattered data and also for solving partial differential equations. For a number of exam-
ples, the results are compared to analytical solutions to demonstrate the accuracy of the
xviii Preface
results obtained. The Halton sequence, which produces pseudo-random data, is intro-
duced to demonstrate how the method readily handles irregular grids and/or scattered
data. A number of globally and compactly supported RBFs are defined and their use
illustrated with examples in 1D, 2D, and 3D. This chapter also includes discussion on the
use of local RBFs, which allow the method to be used on very large problems. Local RBFs
result in the system matrices becoming sparse, which facilitates the application of sparse
matrix methods, which are provided by the R package Matrix.
Chapter 8 introduces the concept of conservation laws in the context of evolution-
ary PDEs. Under the assumption of certain decay conditions, it is shown how conserved
quantities can be identified for particular PDEs. It is then shown that conserved quan-
tities can be used to calculate associated constants of motion or invariants. These con-
stants of motion are very useful in numerical analysis as they can be used to provide
an indication of calculation accuracy. The ideas are discussed mainly in terms of the 1D
Korteweg-de Vries (KdV) equation, where a number of the commonly known conserva-
tion laws applicable to this equation are derived. It is then shown using the Miura and
Gardener transformations that, actually, the KdV equation possesses an infinity of con-
servation laws. The discussion is then extended to the 2D KdV equation and then to the
KdV equation with variable coefficients (vcKdV). This chapter also includes conserva-
tion law discussions and example calculations in relation to the nonlinear Schrödinger
(NLS) equation and the Boussinesq equation.
Chapter 9 is a case study into the analysis of a golf ball in fight. It has been the subject
of many theoretical investigations, with some of the earliest being published in the late
1890s. This case study provides an in-depth study of this subject, with computer simula-
tion results presented and compared to published performance data. The various forces
acting on a golf ball in flight are discussed, namely, drag, Magnus, and gravitational. The
differential equations that describe the golf ball flight are then derived. The effects of
compression, spin, ambient conditions, wind, launch angle, bounce, and roll are all taken
into account in the simulation calculations. The latest coefficients from the literature for
drag and lift are used. The results are presented graphically and compared with measured
statistics for club head speed, carry, and trajectory height for various classes of player,
using different golf clubs. The effect of push, pull, fade, draw, slice, and hook shots are
investigated, and the results are discussed. The magnitude of wind shear at ground level
is calculated, and its effect on a static golf ball is investigated.
Chapter 10 is a case study into the problem of an intense explosion. In 1945, Sir Geof-
frey Ingram Taylor was asked by the British Military Application of Uranium Detona-
tion (MAUD) Committee to deduce information regarding the power of the first atomic
explosion at the Trinity site in the New Mexico desert. He was able to estimate, using
only public domain photographs of the blast, that the yield of the bomb was equivalent
to between 16.8 and 23.7 kilotons of TNT. This case study discusses the subsequent sem-
inal papers that Ingram published and traces the perceptive calculations that he made.
A systems analysis starts with a form of the Euler equations, from which, using similar-
ity analysis, certain important relationships are deduced. With the aid of a set of high-
speed photographs of the detonation, and assuming spherical symmetry, the underly-
ing characteristics of the blast are gradually revealed by a sequence of thermodynamic
calculations. The thermodynamic gas laws required to unravel this puzzle are discussed,
along with shock wave analysis using the Hugonoit–Rankine relations. Kinetic energy
Preface xix
and heat energy integrals are evaluated, leading to a full description of the blast. This
includes blast wave speed, pressure, and temperature over time. Closed-form analytical
solutions to the problem, subsequently published by Sedov in 1959, are presented that
provide a useful check on the accuracy of Ingram’s numerical calculations. A similarity
analysis is included, covering spherical, cylindrical, and planar blast situations.
Chapter 11 is a case study into the global carbon cycle and how increased concen-
trations in atmospheric carbon dioxide have implications for climate change. A simpli-
fied model is presented that considers four fossil-fuel emission scenarios based on the
work of Caldeira and Wickett and how the atmosphere and oceans respond. Air–ocean
interaction is modeled using the wind-driven gas–sea exchange relationship due to Wan-
2−
ninkhof, with the subsequent dispersion of gaseous CO2 into CO2 (aq), HCO− 3 , CO3 ,
and H in accordance with carbonate chemistry equilibria. It is shown how an increasing
+
concentration of positive hydrogen ions causes seawater acidity to rise, that is, a fall in
pH. Seawater buffering calculations are also introduced to demonstrate how the ocean’s
ability to absorb atmospheric CO2 is diminished as seawater concentration of dissolved
inorganic carbon increases. A discussion of solar and terrestrial radiation modeling is
also included, along with calculations that show how increasing CO2 concentrations in
the atmosphere can lead to increases in the Earth’s surface temperature, that is, to the
so-called greenhouse effect.
All chapters include worked examples, many of which generate animations, along
with annotated computer code, which is available for download. As an additional
resource for some chapters, computer code is provided with the downloads for symbolic
computer algebra analysis using Maple and Maxima/wxMaxima systems. Maxima is a
free open-source program available for different operating systems that can be down-
loaded from http://maxima.sourceforge.net/. A GUI-based version, wxMaxima, can be
downloaded from http://andrejv.github.io/wxmaxima/.
To maximize the benefit of studying numerical computing, the learning process should
not be regarded as a passive pursuit. Rather, it should be regarded as a hands-on experi-
mental activity. Because many problems are nonlinear, analytical or well-tried and tested
solutions may not exist. In these situations it may be necessary to try various different
options to find the most appropriate solution technique, with the best parameter values
being deduced by trial and error. This book includes many and varied solutions to a wide
range of problems, and it is hoped that the reader will find some that can be applied
directly, or adapted, to the particular problem of interest.
To conclude, the major focus of this book is the numerical solution of initial value
problems (IVPs) and boundary value problems (BVPs) described by ODEs and PDEs.
The general approach and content complement the author’s earlier books ([Gri-11] and
[Sch-09]) and also the excellent book Solving Differential Equations in R [Soe-12].
ACKNOWLEDGMENTS
I would like to thank Professor William (Bill) E. Schiesser of Lehigh University for col-
laboration in the area of numerical solutions to differential equations over many years
and for suggesting that I look into using the R language for solving ODEs and PDEs;
Professor Alan M. Nathan of the University of Illinois for useful discussions on the flight
of projectiles and for clarifying some concepts; and Professor Duncan Murdoch of the
xx Preface
University of Western Ontario for advice on using the R package rgl and for respond-
ing positively to requests for changes to the 3D graphics function persp3d().
Graham W. Griffiths
Nayland, Suffolk, United Kingdom
June 2015
[email protected]
www.pdecomp.net
REFERENCES
[Cra-11] Crawley, M. J. (2011), The R Book, John Wiley.
[Gri-11] Griffiths, G. W. and W. E. Schiesser (2011), Traveling Wave Solutions of Partial Differential
Equations: Numerical and Analytical Methods with Matlab and Maple, Academic Press.
[Mat-11] Matloff, N. (2011), The Art of R Programming, No Starch Press.
[Sch-09] Schiesser, W. E. and G. W. Griffiths (2009), A Compendium of Partial Differential Equa-
tion Models: Method of Lines Analysis with Matlab, Cambridge University Press.
[Soe-10] Soetaert, K., T. Petzoldt and R. W. Setzer (2010), Solving Differential Equations in R:
Package deSolve, Journal of Statistical Software 33-9, 1–25.
[Soe-12] Soetaert, K., J. Cash and F. Mazzia (2012), Solving Differential Equations in R, Springer-
Verlag.