Professional Documents
Culture Documents
Textbook Finite Difference Computing With Pdes A Modern Software Approach 1St Edition Hans Petter Langtangen Ebook All Chapter PDF
Textbook Finite Difference Computing With Pdes A Modern Software Approach 1St Edition Hans Petter Langtangen Ebook All Chapter PDF
https://textbookfull.com/product/pricing-derivatives-under-levy-
models-modern-finite-difference-and-pseudo-differential-
operators-approach-1st-edition-andrey-itkin-auth/
https://textbookfull.com/product/software-for-exascale-computing-
sppexa-2016-2019-hans-joachim-bungartz/
https://textbookfull.com/product/automating-with-simatic-
controllers-software-programming-data-communication-6th-edition-
hans-berger/
https://textbookfull.com/product/numerical-solution-of-
differential-equations-introduction-to-finite-difference-and-
finite-element-methods-1st-edition-zhilin-li/
Finite Difference Methods in Heat Transfer, Second
Edition M. Necati Özi■ik
https://textbookfull.com/product/finite-difference-methods-in-
heat-transfer-second-edition-m-necati-ozisik/
https://textbookfull.com/product/finite-element-computations-in-
mechanics-with-r-a-problem-centered-programming-approach-1st-
edition-khameel-bayo-mustapha/
https://textbookfull.com/product/engineering-software-as-a-
service-an-agile-approach-using-cloud-computing-first-
edition-1-2-1-edition-fox/
https://textbookfull.com/product/finite-element-computations-in-
mechanics-with-r-a-problem-centered-programming-approach-first-
edition-bayo-mustapha/
https://textbookfull.com/product/a-philosophical-approach-to-
quantum-field-theory-1st-edition-hans-christian-ottinger/
0 u1
u
2
u5
u
u3
u4
16
Finite Difference
Computing
with PDEs
A Modern Software Approach Editorial Board
T. J.Barth
M.Griebel
D.E.Keyes
R.M.Nieminen
D.Roose
T.Schlick
Texts in Computational
Science and Engineering
16
Editors
Timothy J. Barth
Michael Griebel
David E. Keyes
Risto M. Nieminen
Dirk Roose
Tamar Schlick
More information about this series at
http://www.springer.com/series/5151
Hans Petter Langtangen Svein Linge
Finite Difference
Computing with PDEs
A Modern Software Approach
Hans Petter Langtangen Svein Linge
Lysaker, Norway Process, Energy & Environmental
Technology
University College of Southeast Norway
Porsgrunn, Norway
ISSN 1611-0994
Texts in Computational Science and Engineering
ISBN 978-3-319-55455-6 ISBN 978-3-319-55456-3 (eBook)
DOI 10.1007/978-3-319-55456-3
© The Editor(s) (if applicable) and The Author(s) 2017 This book is an open access publication
Open Access This book is distributed under the terms of the Creative Commons Attribution 4.0 Interna-
tional License (http://creativecommons.org/licenses/by/4.0/), which permits use, duplication, adaptation,
distribution and reproduction in any medium or format, as long as you give appropriate credit to the orig-
inal author(s) and the source, provide a link to the Creative Commons license and indicate if changes
were made.
The images or other third party material in this book are included in the work’s Creative Commons li-
cense, unless indicated otherwise in the credit line; if such material is not included in the work’s Creative
Commons license and the respective action is not permitted by statutory regulation, users will need to
obtain permission from the license holder to duplicate, adapt or reproduce the material.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publica-
tion does not imply, even in the absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, express or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
There are so many excellent books on finite difference methods for ordinary and
partial differential equations that writing yet another one requires a different view
on the topic. The present book is not so concerned with the traditional academic
presentation of the topic, but is focused at teaching the practitioner how to obtain
reliable computations involving finite difference methods. This focus is based on a
set of learning outcomes:
Compared to other textbooks, the present one has a particularly strong emphasis
on computer implementation and verification. It also has a strong emphasis on an
intuitive understanding of constructing finite difference methods. To learn about
the potential non-physical artifacts of various methods, we study exact solutions
of finite difference schemes as these give deeper insight into the physical behavior
of the numerical methods than the traditional (and more general) asymptotic error
analysis. However, asymptotic results regarding convergence rates, typically trun-
cation errors, are crucial for testing implementations, so an extensive appendix is
devoted to the computation of truncation errors.
Why finite differences? One may ask why we do finite differences when finite
element and finite volume methods have been developed to greater generality and
sophistication than finite differences and can cover more problems. The finite ele-
ment and finite volume methods are also the industry standard nowadays. Why not
just those methods? The reason for finite differences is the method’s simplicity, both
from a mathematical and coding perspective. Especially in academia, where simple
model problems are used a lot for teaching and in research (e.g., for verification of
advanced implementations), there is a constant need to solve the model problems
from scratch with easy-to-verify computer codes. Here, finite differences are ideal.
A simple 1D heat equation can of course be solved by a finite element package, but
a 20-line code with a difference scheme is just right to the point and provides an
v
vi Preface
understanding of all details involved in the model and the solution method. Every-
body nowadays has a laptop and the natural method to attack a 1D heat equation is
a simple Python or Matlab program with a difference scheme. The conclusion goes
for other fundamental PDEs like the wave equation and Poisson equation as long
as the geometry of the domain is a hypercube. The present book contains all the
practical information needed to use the finite difference tool in a safe way.
Various pedagogical elements are utilized to reach the learning outcomes, and
these are commented upon next.
Some people think that stiff challenges are the best device to induce learning, but I am not
one of them. The natural way to learn something is by spending vast amounts of easy,
enjoyable time at it. This goes whether you want to speak German, sight-read at the piano,
type, or do mathematics. Give me the German storybook for fifth graders that I feel like
reading in bed, not Goethe and a dictionary. The latter will bring rapid progress at first,
then exhaustion and failure to resolve.
The main thing to be said for stiff challenges is that inevitably we will encounter them,
so we had better learn to face them boldly. Putting them in the curriculum can help teach
us to do so. But for teaching the skill or subject matter itself, they are overrated. [18, p. 86]
Lloyd N. Trefethen, Applied Mathematician, 1955-.
minimum of mathematical details. The text should therefore have a potential for
use early in undergraduate student programs.
All nuts and bolts Many have experienced that “vast amounts of easy, enjoyable
time”, as stated in the quote above, arises when mathematics is implemented on
a computer. The implementation process triggers understanding, creativity, and
curiosity, but many students find the transition from a mathematical algorithm to a
working code difficult and spend a lot of time on “programming issues”.
Most books on numerical methods concentrate on the mathematics of the subject
while details on going from the mathematics to a computer implementation are
less in focus. A major purpose of this text is therefore to help the practitioner by
providing all nuts and bolts necessary for safely going from the mathematics to a
well-designed and well-tested computer code. A significant portion of the text is
consequently devoted to programming details.
Vectorized code Finite difference methods lead to code with loops over large ar-
rays. Such code in plain Python is known to run slowly. We demonstrate, especially
in Appendix C, how to port loops to fast, compiled code in C or Fortran. However,
an alternative is to vectorize the code to get rid of explicit Python loops, and this
technique is met throughout the book. Vectorization becomes closely connected to
the underlying array library, here numpy, and is often thought of as a difficult sub-
ject by students. Through numerous examples in different contexts, we hope that
the present book provides a substantial contribution to explaining how algorithms
can be vectorized. Not only will this speed up serial code, but with a library that can
produce parallel code from numpy commands (such as Numba1 ), vectorized code
can be automatically turned into parallel code and utilize multi-core processors and
GPUs. Also when creating tailored parallel code for today’s supercomputers, vec-
torization is useful as it emphasizes splitting up an algorithm into plain and simple
1
http://numba.pydata.org
viii Preface
array operations, where each operation is trivial to parallelize efficiently, rather than
trying to develop a “smart” overall parallelization strategy.
Limited scope The aim of this book is not to give an overview of a lot of methods
for a wide range of mathematical models. Such information can be found in numer-
ous existing, more advanced books. The aim is rather to introduce basic concepts
and a thorough understanding of how to think about computing with finite differ-
ence methods. We therefore go in depth with only the most fundamental methods
and equations. However, we have a multi-disciplinary scope and address the inter-
play of mathematics, numerics, computer science, and physics.
Independent chapters Most book authors are careful with avoiding repetitions of
material. The chapters in this book, however, contain some overlap, because we
want the chapters to appear meaningful on their own. Modern publishing technol-
ogy makes it easy to take selected chapters from different books to make a new book
tailored to a specific course. The more a chapter builds on details in other chapters,
the more difficult it is to reuse chapters in new contexts. Also, most readers find it
Preface ix
convenient that important information is explicitly stated, even if it was already met
in another chapter.
Supplementary materials All program and data files referred to in this book are
available from the book’s primary web site: URL: http://github.com/hplgit/fdm-
book/.
1 Vibration ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Finite Difference Discretization . . . . . . . . . . . . . . . . . . . . . . 1
1.1.1 A Basic Model for Vibrations . . . . . . . . . . . . . . . . . 1
1.1.2 A Centered Finite Difference Scheme . . . . . . . . . . . . 2
1.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.1 Making a Solver Function . . . . . . . . . . . . . . . . . . . . 4
1.2.2 Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.3 Scaled Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 Visualization of Long Time Simulations . . . . . . . . . . . . . . . . 11
1.3.1 Using a Moving Plot Window . . . . . . . . . . . . . . . . . 11
1.3.2 Making Animations . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3.3 Using Bokeh to Compare Graphs . . . . . . . . . . . . . . . 15
1.3.4 Using a Line-by-Line Ascii Plotter . . . . . . . . . . . . . . 18
1.3.5 Empirical Analysis of the Solution . . . . . . . . . . . . . . 19
1.4 Analysis of the Numerical Scheme . . . . . . . . . . . . . . . . . . . . 21
1.4.1 Deriving a Solution of the Numerical Scheme . . . . . . . 21
1.4.2 The Error in the Numerical Frequency . . . . . . . . . . . . 22
1.4.3 Empirical Convergence Rates and Adjusted ! . . . . . . . 24
1.4.4 Exact Discrete Solution . . . . . . . . . . . . . . . . . . . . . 24
1.4.5 Convergence . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.4.6 The Global Error . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.4.7 Stability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.4.8 About the Accuracy at the Stability Limit . . . . . . . . . . 27
1.5 Alternative Schemes Based on 1st-Order Equations . . . . . . . . . 29
1.5.1 The Forward Euler Scheme . . . . . . . . . . . . . . . . . . . 29
1.5.2 The Backward Euler Scheme . . . . . . . . . . . . . . . . . . 30
1.5.3 The Crank-Nicolson Scheme . . . . . . . . . . . . . . . . . . 30
1.5.4 Comparison of Schemes . . . . . . . . . . . . . . . . . . . . . 32
1.5.5 Runge-Kutta Methods . . . . . . . . . . . . . . . . . . . . . . 33
1.5.6 Analysis of the Forward Euler Scheme . . . . . . . . . . . . 34
1.6 Energy Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.6.1 Derivation of the Energy Expression . . . . . . . . . . . . . 36
1.6.2 An Error Measure Based on Energy . . . . . . . . . . . . . . 38
xi
xii Contents
2 Wave Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
2.1 Simulation of Waves on a String . . . . . . . . . . . . . . . . . . . . . 93
2.1.1 Discretizing the Domain . . . . . . . . . . . . . . . . . . . . . 94
2.1.2 The Discrete Solution . . . . . . . . . . . . . . . . . . . . . . 94
2.1.3 Fulfilling the Equation at the Mesh Points . . . . . . . . . . 94
2.1.4 Replacing Derivatives by Finite Differences . . . . . . . . . 95
2.1.5 Formulating a Recursive Algorithm . . . . . . . . . . . . . . 96
2.1.6 Sketch of an Implementation . . . . . . . . . . . . . . . . . . 98
2.2 Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
2.2.1 A Slightly Generalized Model Problem . . . . . . . . . . . 99
2.2.2 Using an Analytical Solution of Physical Significance . . 99
Contents xiii
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
List of Exercises, Problems and Projects
xxi
xxii List of Exercises, Problems and Projects
Exercise 2.7: Find the analytical solution to a damped wave equation . . . . . 148
Problem 2.8: Explore symmetry boundary conditions . . . . . . . . . . . . . . . 148
Exercise 2.9: Send pulse waves through a layered medium . . . . . . . . . . . . 148
Exercise 2.10: Explain why numerical noise occurs . . . . . . . . . . . . . . . . 149
Exercise 2.11: Investigate harmonic averaging in a 1D model . . . . . . . . . . 149
Problem 2.12: Implement open boundary conditions . . . . . . . . . . . . . . . . 149
Exercise 2.13: Implement periodic boundary conditions . . . . . . . . . . . . . . 151
Exercise 2.14: Compare discretizations of a Neumann condition . . . . . . . . 151
Exercise 2.15: Verification by a cubic polynomial in space . . . . . . . . . . . . 152
Exercise 2.16: Check that a solution fulfills the discrete model . . . . . . . . . 181
Project 2.17: Calculus with 2D mesh functions . . . . . . . . . . . . . . . . . . . 181
Exercise 2.18: Implement Neumann conditions in 2D . . . . . . . . . . . . . . . 182
Exercise 2.19: Test the efficiency of compiled loops in 3D . . . . . . . . . . . . 182
Exercise 2.20: Simulate waves on a non-homogeneous string . . . . . . . . . . 195
Exercise 2.21: Simulate damped waves on a string . . . . . . . . . . . . . . . . . 195
Exercise 2.22: Simulate elastic waves in a rod . . . . . . . . . . . . . . . . . . . . 195
Exercise 2.23: Simulate spherical waves . . . . . . . . . . . . . . . . . . . . . . . 195
Problem 2.24: Earthquake-generated tsunami over a subsea hill . . . . . . . . . 196
Problem 2.25: Earthquake-generated tsunami over a 3D hill . . . . . . . . . . . 198
Problem 2.26: Investigate Mayavi for visualization . . . . . . . . . . . . . . . . . 199
Problem 2.27: Investigate visualization packages . . . . . . . . . . . . . . . . . . 199
Problem 2.28: Implement loops in compiled languages . . . . . . . . . . . . . . 199
Exercise 2.29: Simulate seismic waves in 2D . . . . . . . . . . . . . . . . . . . . 200
Project 2.30: Model 3D acoustic waves in a room . . . . . . . . . . . . . . . . . 200
Project 2.31: Solve a 1D transport equation . . . . . . . . . . . . . . . . . . . . . 201
Problem 2.32: General analytical solution of a 1D damped wave equation . . 204
Problem 2.33: General analytical solution of a 2D damped wave equation . . 205
Exercise 3.1: Explore symmetry in a 1D problem . . . . . . . . . . . . . . . . . . 242
Exercise 3.2: Investigate approximation errors from a ux D 0 boundary
condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Exercise 3.3: Experiment with open boundary conditions in 1D . . . . . . . . . 243
Exercise 3.4: Simulate a diffused Gaussian peak in 2D/3D . . . . . . . . . . . . 244
Exercise 3.5: Examine stability of a diffusion model with a source term . . . . 245
Exercise 3.6: Stabilizing the Crank-Nicolson method by Rannacher time
stepping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Project 3.7: Energy estimates for diffusion problems . . . . . . . . . . . . . . . . 316
Exercise 3.8: Splitting methods and preconditioning . . . . . . . . . . . . . . . . 318
Problem 3.9: Oscillating surface temperature of the earth . . . . . . . . . . . . . 319
Problem 3.10: Oscillating and pulsating flow in tubes . . . . . . . . . . . . . . . 320
Problem 3.11: Scaling a welding problem . . . . . . . . . . . . . . . . . . . . . . 320
Exercise 3.12: Implement a Forward Euler scheme for axi-symmetric diffusion 322
Exercise 4.1: Analyze 1D stationary convection-diffusion problem . . . . . . . 351
Exercise 4.2: Interpret upwind difference as artificial diffusion . . . . . . . . . 351
Problem 5.1: Determine if equations are nonlinear or not . . . . . . . . . . . . . 401
Problem 5.2: Derive and investigate a generalized logistic model . . . . . . . . 401
Problem 5.3: Experience the behavior of Newton’s method . . . . . . . . . . . . 402
Exercise 5.4: Compute the Jacobian of a 2 2 system . . . . . . . . . . . . . . . 402
Problem 5.5: Solve nonlinear equations arising from a vibration ODE . . . . . 402
List of Exercises, Problems and Projects xxiii
Exercise 5.6: Find the truncation error of arithmetic mean of products . . . . . 402
Problem 5.7: Newton’s method for linear problems . . . . . . . . . . . . . . . . 404
Problem 5.8: Discretize a 1D problem with a nonlinear coefficient . . . . . . . 404
Problem 5.9: Linearize a 1D problem with a nonlinear coefficient . . . . . . . 404
Problem 5.10: Finite differences for the 1D Bratu problem . . . . . . . . . . . . 404
Problem 5.11: Discretize a nonlinear 1D heat conduction PDE by finite
differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Problem 5.12: Differentiate a highly nonlinear term . . . . . . . . . . . . . . . . 405
Exercise 5.13: Crank-Nicolson for a nonlinear 3D diffusion equation . . . . . 406
Problem 5.14: Find the sparsity of the Jacobian . . . . . . . . . . . . . . . . . . . 406
Problem 5.15: Investigate a 1D problem with a continuation method . . . . . . 406
Exercise B.1: Truncation error of a weighted mean . . . . . . . . . . . . . . . . . 447
Exercise B.2: Simulate the error of a weighted mean . . . . . . . . . . . . . . . . 447
Exercise B.3: Verify a truncation error formula . . . . . . . . . . . . . . . . . . . 447
Problem B.4: Truncation error of the Backward Euler scheme . . . . . . . . . . 447
Exercise B.5: Empirical estimation of truncation errors . . . . . . . . . . . . . . 448
Exercise B.6: Correction term for a Backward Euler scheme . . . . . . . . . . . 448
Problem B.7: Verify the effect of correction terms . . . . . . . . . . . . . . . . . 448
Problem B.8: Truncation error of the Crank-Nicolson scheme . . . . . . . . . . 448
Problem B.9: Truncation error of u0 D f .u; t/ . . . . . . . . . . . . . . . . . . . 448
Exercise B.10: Truncation error of ŒD t D t un . . . . . . . . . . . . . . . . . . . . 449
Exercise B.11: Investigate the impact of approximating u0 .0/ . . . . . . . . . . 449
Problem B.12: Investigate the accuracy of a simplified scheme . . . . . . . . . 449
Exercise C.1: Explore computational efficiency of numpy.sum versus built-in
sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
Exercise C.2: Make an improved numpy.savez function . . . . . . . . . . . . . 490
Exercise C.3: Visualize the impact of the Courant number . . . . . . . . . . . . 491
Exercise C.4: Visualize the impact of the resolution . . . . . . . . . . . . . . . . 491
Vibration ODEs
1
The simplest model of a vibrating mechanical system has the following form:
Here, ! and I are given constants. Section 1.12.1 derives (1.1) from physical prin-
ciples and explains what the constants mean.
The exact solution of (1.1) is
That is, u oscillates with constant amplitude I and angular frequency !. The corre-
sponding period of oscillations (i.e., the time between two neighboring peaks in the
cosine function) is P D 2=!. The number of periods per second is f D !=.2/
and measured in the unit Hz. Both f and ! are referred to as frequency, but ! is
more precisely named angular frequency, measured in rad/s.
In vibrating mechanical systems modeled by (1.1), u.t/ very often represents
a position or a displacement of a particular point in the system. The derivative
u0 .t/ then has the interpretation of velocity, and u00 .t/ is the associated acceleration.
The model (1.1) is not only applicable to vibrating mechanical systems, but also to
oscillations in electrical circuits.
To formulate a finite difference method for the model problem (1.1), we follow the
four steps explained in Section 1.1.2 in [9].
Step 2: Fulfilling the equation at discrete time points The ODE is to be satisfied
at each mesh point where the solution must be found:
u1 u1
D 0: (1.6)
2t
1.1 Finite Difference Discretization 3
Computing the first step We observe that (1.7) cannot be used for n D 0 since
the computation of u1 then involves the undefined value u1 at t D t. The
discretization of the initial condition then comes to our rescue: (1.6) implies u1 D
u1 and this relation can be combined with (1.7) for n D 0 to yield a value for u1 :
u1 D 2u0 u1 t 2 ! 2 u0 ;
which reduces to
1
u1 D u0 t 2 ! 2 u0 : (1.8)
2
Exercise 1.5 asks you to perform an alternative derivation and also to generalize the
initial condition to u0 .0/ D V ¤ 0.
1. u0 D I
2. compute u1 from (1.8)
3. for n D 1; 2; : : : ; N t 1: compute unC1 from (1.7)
u[0] = I
u[1] = u[0] - 0.5*dt**2*w**2*u[0]
for n in range(1, Nt):
u[n+1] = 2*u[n] - u[n-1] - dt**2*w**2*u[n]
1
http://en.wikipedia.org/wiki/Verlet_integration
4 1 Vibration ODEs
Operator notation We may write the scheme using a compact difference notation
listed in Appendix A.1 (see also Section 1.1.8 in [9]). The difference (1.4) has the
operator notation ŒD t D t un such that we can write:
ŒD t D t u C ! 2 u D 0n : (1.9)
Note that ŒD t D t un means applying a central difference with step t=2 twice:
1 1
ŒD t unC 2 ŒD t un 2
ŒD t .D t u/n D
t
which is written out as
1 unC1 un un un1 unC1 2un C un1
D :
t t t t 2
unC1 un1
ŒD2t un D : (1.11)
2t
1.2 Implementation
The algorithm from the previous section is readily translated to a complete Python
function for computing and returning u0 ; u1 ; : : : ; uN t and t0 ; t1 ; : : : ; tN t , given the
input I , !, t, and T :
import numpy as np
import matplotlib.pyplot as plt
u[0] = I
u[1] = u[0] - 0.5*dt**2*w**2*u[0]
for n in range(1, Nt):
u[n+1] = 2*u[n] - u[n-1] - dt**2*w**2*u[n]
return u, t
1.2 Implementation 5
We have imported numpy and matplotlib under the names np and plt, respec-
tively, as this is very common in the Python scientific computing community and
a good programming habit (since we explicitly see where the different functions
come from). An alternative is to do from numpy import * and a similar “import
all” for Matplotlib to avoid the np and plt prefixes and make the code as close as
possible to MATLAB. (See Section 5.1.4 in [9] for a discussion of the two types of
import in Python.)
A function for plotting the numerical and the exact solution is also convenient to
have:
I = 1
w = 2*pi
dt = 0.05
num_periods = 5
P = 2*pi/w # one period
T = P*num_periods
u, t = solver(I, w, dt, T)
visualize(u, t, I, w, dt)
Adjusting some of the input parameters via the command line can be handy.
Here is a code segment using the ArgumentParser tool in the argparse module
to define option value (–option value) pairs on the command line:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(’--I’, type=float, default=1.0)
parser.add_argument(’--w’, type=float, default=2*pi)
parser.add_argument(’--dt’, type=float, default=0.05)
parser.add_argument(’--num_periods’, type=int, default=5)
a = parser.parse_args()
I, w, dt, num_periods = a.I, a.w, a.dt, a.num_periods
6 1 Vibration ODEs
Such parsing of the command line is explained in more detail in Section 5.2.3 in
[9].
A typical execution goes like
Terminal
unC1 un1
v.tn / D u0 .tn / v n D D ŒD2t un : (1.12)
2t
This formula applies for all inner mesh points, n D 1; : : : ; N t 1. For n D 0, v.0/
is given by the initial condition on u0 .0/, and for n D N t we can use a one-sided,
backward difference:
un un1
v n D ŒD t un D :
t
Typical (scalar) code is
v = np.zeros_like(u) # or v = np.zeros(len(u))
# Use central difference for internal points
for i in range(1, len(u)-1):
v[i] = (u[i+1] - u[i-1])/(2*dt)
# Use initial condition for u’(0) when i=0
v[0] = 0
# Use backward difference at the final mesh point
v[-1] = (u[-1] - u[-2])/dt
Since the loop is slow for large N t , we can get rid of the loop by vectorizing the
central difference. The above code segment goes as follows in its vectorized version
(see Problem 1.2 in [9] for explanation of details):
v = np.zeros_like(u)
v[1:-1] = (u[2:] - u[:-2])/(2*dt) # central difference
v[0] = 0 # boundary condition u’(0)
v[-1] = (u[-1] - u[-2])/dt # backward difference
1.2.2 Verification
def test_three_steps():
from math import pi
I = 1; w = 2*pi; dt = 0.1; T = 1
u_by_hand = np.array([1.000000000000000,
0.802607911978213,
0.288358920740053])
u, t = solver(I, w, dt, T)
diff = np.abs(u_by_hand - u[:3]).max()
tol = 1E-14
assert diff < tol
This function is a proper test function, compliant with the pytest and nose testing
framework for Python code, because
We shall in this book implement all software verification via such proper test func-
tions, also known as unit testing. See Section 5.3.2 in [9] for more details on how to
construct test functions and utilize nose or pytest for automatic execution of tests.
Our recommendation is to use pytest. With this choice, you can run all test functions
in vib_undamped.py by
Terminal
vib_undamped.py::test_three_steps PASSED
vib_undamped.py::test_convergence_rates PASSED
Testing very simple polynomial solutions Constructing test problems where the
exact solution is constant or linear helps initial debugging and verification as one
expects any reasonable numerical method to reproduce such solutions to machine
precision. Second-order accurate methods will often also reproduce a quadratic
solution. Here ŒD t D t t 2 n D 2, which is the exact result. A solution u D t 2
leads to u00 C ! 2 u D 2 C .!t/2 ¤ 0. We must therefore add a source in the
equation: u00 C ! 2 u D f to allow a solution u D t 2 for f D 2 C .!t/2 . By
simple insertion we can show that the mesh function un D tn2 is also a solution of
the discrete equations. Problem 1.1 asks you to carry out all details to show that
linear and quadratic solutions are solutions of the discrete equations. Such results
are very useful for debugging and verification. You are strongly encouraged to do
this problem now!
Such, then, were the “Works” of this truly great man. And it
appears that they were, in general, not only arduous in their
execution, and highly beneficial in their uses and effects; but that
they were likewise the productions of a lofty, penetrating and active
genius, great knowledge and skill, and the most indefatigable
perseverance.[376]
IN MEMORY OF
DAVID RITTENHOUSE,
BORN APRIL 8th, 1732,
AND
HANNAH RITTENHOUSE,
HIS WIFE,
1799,
Aged 64 years.
303. “Astronomy, like the Christian religion, if you will allow me the
comparison,” said our philosopher, “has a much greater influence on
our knowledge in general, and perhaps on our manners too, than is
commonly imagined. Though but few men are its particular votaries,
yet the Light it affords is universally diffused among us; and it is
difficult for us to divest ourselves of its influence so far, as to frame
any competent idea of what would be our situation without it.” See
Ritt. Orat.
305. The elder of these ladies became, in the year 1788, the
second wife of Jonathan Dickinson Sergeant, Esq. late an eminent
lawyer in Philadelphia, and sometime attorney-general of
Pennsylvania. This gentleman was one of the five persons
delegated, on the 20th of February, 1776, by the convention of New-
Jersey (where he then resided,) to represent that colony in congress:
his colleagues were, the late governor Livingston, and John de Hart,
Richard Smith, and John Cooper, Esquires. Mr. Sergeant died of the
yellow fever in Philadelphia, on the 8th of October, 1793; after having
been many weeks actively and benevolently employed, with a few
other gentlemen of humanity, in the prosecution of such measures,
as the sufferings of those of the citizens who had not fled, and the
general welfare of the city required, at that calamitous period. He left
issue a son and two daughters, by this marriage, besides several
children by his first wife.
306. Dr. Rush has very beautifully expressed the same sentiment,
in a passage of his Eulogium on our philosopher. After remarking,
that his bodily infirmities “contributed much to the perfection of his
virtue, by producing habitual patience and resignation to the will of
heaven, and a constant eye to the hour of his dissolution,” he says:
“It was a window through which he often looked with pleasure
towards a place of existence, where, from the increase and
perfection of his intuitive faculties, he would probably acquire more
knowledge in an hour, than he had acquired in his whole life, by the
slow operations of reason; and where, from the greater magnitude
and extent of the objects of his contemplation, his native globe would
appear like his cradle, and all the events of time, like the
amusements of his infant years.” Such, too, must have been the
ideas, impressed on the mind of Rittenhouse himself, when, in the
morning of his life, he imagined the angel Gabriel looking down from
the seat of perfect knowledge, and viewing, benignly, far from
beholding with a smile of contempt, the efforts of Newton, to
demonstrate the actual motion of our earth. W. B.
309. See Mr. Malone’s Account of the Life and Writings of Sir
Joshua Reynolds, prefixed to the works of Sir Joshua.
311. “His manners were civil and engaging, to such a degree, that
he seldom passed an hour, even in a public house in travelling
through our country, without being followed by the good wishes of all
who attended upon him.” Rush’s Eulogium on Ritt.
318. In the year 1756, he made an eight-day clock, for his brother-
in-law, Mr. Barton; over the dial-plate of which, was engraven this
mementory motto—Tempus fugit; and underneath, this blunt but too
often necessary precept—Go about your business.
325. A second edition of the first volume was published in the year
1789, in consequence of the extraordinary demand for that book, by
reason of the very important papers respecting the Transit of Venus,
contained in it.
326. Some further remarks respecting this comet, than those
contained in Dr. Rittenhouse’s communication, here referred to, will
be found in an extract which has already been given, of his letter to
the Rev. Mr. Barton, under the date of July 30, 1770.
330. This eclipse was observed by Andrew Ellicott, Esq. at the city
of Washington, as follows; viz.