Companion Website

Computational Physics

From Equations to Simulation

Chapter 6

Numerical Differentiation

The programs below provide compact reference implementations of two numerical differentiation methods discussed in Chapter 6. Each step of the algorithms is kept explicit, making it easy to compare the same calculation in MATLAB, Python, C++, and Fortran. The examples distinguish differentiation of tabulated data from differentiation of a function that can be evaluated at arbitrary points. For larger scientific applications, tested library routines may be preferable; see the Chapter 6 Resources page for language-specific options.

Program MATLAB Python C++ Fortran
Derivatives from tabulated data First and second derivatives of uniformly or nonuniformly spaced data using local four-point Lagrange interpolation, with the stencil shifted near the endpoints. Intended for smooth data, since numerical differentiation amplifies noise. Download Download Download Download
Centered differences with Richardson extrapolation First and second derivatives of a function evaluated with centered differences at step sizes h and h/2, then improved from O(h2) to O(h4) by Richardson extrapolation. The program also reports the magnitude of the Richardson correction as an error indicator. Download Download Download Download

← Back to Chapter 6