Complex contour integration
| Problem | Compute along a path in the complex plane; residues, derivatives of analytic functions and winding numbers |
| Devised by | Augustin-Louis Cauchy (integral theorem 1825, residues 1826, integral formula 1831); numerical differentiation by contour integrals: James Lyness and Cleve Moler (1967) |
| Accuracy | Adaptive Gauss-Kronrod to a relative tolerance on each segment; the trapezoid rule on a circle converges exponentially |
| Cost | At least 60 evaluations per segment, more where the integrand varies quickly |
| Read first | Newton-Cotes rules: midpoint, trapezoid and Simpson, Preliminaries: complex numbers |
| API | contour_integral, Contour, PathSegment, residue, cauchy_derivative, winding_number |
Overview
Integrals of complex functions along curves are the central tool of complex analysis, and they are surprisingly practical. They turn difficult real integrals into easy ones, compute derivatives of any order from function values alone, count the zeros of a function inside a region, and evaluate inverse Laplace transforms and special functions. Numerically, a contour integral is an ordinary integral in disguise: parametrise the path as and integrate over the parameter, using any of the quadrature rules of this chapter.
The library integrates along contours built from straight lines, circular arcs and arbitrary parametrised curves, with an adaptive Gauss-Kronrod rule on each piece. On top of this are the classical tools: residues, Cauchy’s formula for derivatives and the winding number.
Where it is used
Integrals in the complex plane turn up where real-variable methods fail or are slow.
- Signal processing and control. Inverse Laplace and Z-transforms, and stability checks via the argument principle (Nyquist criterion), are contour integrals.
- Physics. Residues evaluate integrals in scattering theory, statistical mechanics and electromagnetics.
- Numerical analysis. Cauchy’s formula gives derivatives and matrix functions to high accuracy, and the trapezoid rule on a circle converges geometrically.
- Counting roots. The number of zeros of a function inside a region is a contour integral.
History
Complex integration grew out of attempts to evaluate real definite integrals. In 1814 Augustin- Louis Cauchy presented a memoir on definite integrals in which he noticed that changing the order of integration in certain double integrals gave different answers, and traced the difference to singular points. His Mémoire sur les intégrales définies prises entre des limites imaginaires (1825) states what is now Cauchy’s integral theorem: the integral of an analytic function between two points does not depend on the path. In 1826 he introduced the calculus of residues, and in 1831, in exile in Turin, he published the integral formula that expresses an analytic function, and all its derivatives, through its values on a surrounding curve.
The numerical use of these formulas came much later. In 1967 James Lyness and Cleve Moler showed how to compute high derivatives of analytic functions accurately from contour integrals, and Lyness and Leonard Delves used contour integrals to locate the zeros of analytic functions. Folkmar Bornemann (2011) explained precisely how to choose the radius of the circle so that these computations remain stable.
The idea
Parametrisation
If the path is traced by for , then
an ordinary integral of a complex-valued function of a real variable. A straight line from to has and ; a circular arc has and . The real and imaginary parts can be integrated together by any real quadrature rule with complex arithmetic.
Cauchy’s theorem and residues
Cauchy’s integral theorem. If is analytic on and inside a closed contour , then .
When has isolated singularities inside , the integral picks up a contribution from each. Near , has a Laurent series , and of all its terms only survives integration around a small circle, since for and otherwise. The coefficient is the residue, and
for a counter-clockwise contour. residue
computes as around a small circle about
.
Real integrals by closing the contour
The residue theorem evaluates many real integrals. For , close the real segment with the semicircle in the upper half-plane. The only pole inside is , with residue , so the closed integral is for every . As grows the arc’s contribution, bounded by , vanishes, and the segment tends to the real integral. The library computes each piece:
Table 2.16. Contributions of the segment and the arc to a closed contour integral.
| radius | segment | arc | closed contour | |
|---|---|---|---|---|
| 2 | 2.214297435588 | +9.273e-1 | 3.141592653590 | 3.141592653590 |
| 10 | 2.942255348607 | +1.993e-1 | 3.141592653590 | 3.141592653590 |
| 100 | 3.121593320216 | +2.000e-2 | 3.141592653590 | 3.141592653590 |
| 1000 | 3.139592654256 | +2.000e-3 | 3.141592653590 | 3.141592653590 |
The two parts change with , but their sum is to every digit shown.
Cauchy’s integral formula and derivatives
Cauchy’s integral formula. If is analytic on and inside a circle about , then for every
This turns differentiation, the classic ill-conditioned numerical operation, into integration, which is well-conditioned. Finite differences must balance truncation error against cancellation and lose accuracy rapidly for high derivatives; the Cauchy formula only needs values of on a circle.
The radius still matters, as the figure shows for at :
Figure 2.12. Cauchy derivative error against radius.
On a small circle the integrand is huge, about , while the result is of order one: rounding errors in the integrand are amplified by roughly . On a large circle itself becomes large ( here) and the integral is a small difference of large values. Between the two lies a range of radii where the derivative is accurate almost to machine precision, and it moves outwards as grows. Bornemann showed that the optimal radius is related to the growth of the Taylor coefficients of ; for an entire function like , the best radius for the -th derivative is about .
The trapezoid rule on a circle
On a circle the integrand is a smooth periodic function of , so the trapezoid rule with equally spaced angles converges exponentially:
This is also a discrete Fourier transform: the Taylor coefficients of are, up to scaling, the DFT of its values on a circle, which is why the FFT is the fast way to compute many Taylor coefficients at once.
Figure 2.13. Trapezoid rule against Gauss-Kronrod on a circle.
The trapezoid rule reaches machine precision with about 16 evaluations. The adaptive Gauss-Kronrod rule, which does not know the integrand is periodic, starts with four 15-point panels, so even its loosest tolerance costs over a hundred evaluations (and already gives full accuracy here). The library uses Gauss-Kronrod for every segment because it also handles lines and arbitrary curves, where nothing is periodic, and because it provides an error estimate; when you integrate around full circles many times, the trapezoid rule is the better tool (Exercise 2).
The winding number
The winding number of a closed curve about a point counts how many times the curve goes around counter-clockwise:
For a polygon it can be computed exactly without quadrature: the integral is the total change in
the argument of along the edges, divided by , and the change along each edge is the
angle it subtends at . winding_number
adds these angles with atan2, returns an integer for any simple or self-intersecting polygon,
and returns None when lies on the boundary. The winding number appears in the general
residue theorem, where each residue is weighted by , and in computational
geometry as a robust point-in-polygon test.
Algorithm
contour_integral(f, Γ, tol): for each segment with parameter interval :
- Split into four panels and apply the 15-point Gauss-Kronrod rule to on each, estimating . A non-finite value means the path passes through a singularity: fail.
- Process panels from a stack: accept a panel when (its share, by width out of , of the tolerance relative to ); otherwise bisect it.
- Panels deeper than 40 levels, or beyond two million evaluations in total, are accepted as they are; if that leaves the total estimated error more than ten times the tolerance, fail.
Return the sum of the accepted Kronrod values over all segments, with the summed error estimates and the number of evaluations.
Implementation
The core is the 15-point Gauss-Kronrod rule of the previous entry, applied to the complex integrand. Two details deserve comment.
The scale of the tolerance. The tolerance is relative to , not to the integral itself. Contour integrals are often small because of cancellation: is , about , while the integrand has modulus about . Rounding errors are proportional to , so no method can deliver accuracy relative to the integral itself, and asking for it only causes endless subdivision.
Starting with several panels. An integrand that oscillates many times along a segment, such as around a circle, can be aliased by a single 15-point rule: both the Gauss and the Kronrod estimates come out wrong but nearly equal, and the panel looks converged. Starting every segment with four panels makes this much less likely. No finite set of samples can rule it out entirely; when an integrand is known to oscillate rapidly, split the path into more segments.
In practice
//! Contour integrals in the complex plane: residues, Cauchy's formula and winding numbers.
//!
//! Run with `cargo run -p lib_jsl_integration --example quadrature_contour`.
use lib_jsl_integration::complex_path_integrals::{C64, Contour, PathSegment, cauchy_derivative, contour_integral, residue, winding_number};
use std::f64::consts::PI;
fn main() {
let i = C64::new(0.0, 1.0);
// Cauchy's theorem: an analytic function integrates to zero around a closed path.
let square = Contour::rectangle(C64::new(-1.0, -1.0), C64::new(1.0, 1.0));
let r = contour_integral(|z| z.exp() * z.sin(), &square, 1e-12).unwrap();
println!("∮ eᶻ sin z dz around a square = {:.1e} ({} evaluations)", r.value.norm(), r.nfev);
// A pole inside: ∮ dz/z = 2πi.
let r = contour_integral(|z| z.inv(), &Contour::circle(C64::new(0.2, 0.1), 1.0), 1e-12).unwrap();
println!("∮ dz/z = {:.12} (2πi = {:.12}i)", r.value, 2.0 * PI);
// The residue of 1/(z² + 1) at i is 1/(2i).
let res = residue(|z| (z * z + 1.0).inv(), i, 0.5, 1e-12).unwrap();
println!("Res(1/(z²+1), i) = {res:.12}");
// A real integral by closing the contour in the upper half-plane: ∫ dx/(1+x²) = π.
let r_big = 50.0;
let semicircle = Contour::new(vec![
PathSegment::line(C64::new(-r_big, 0.0), C64::new(r_big, 0.0)),
PathSegment::arc(C64::new(0.0, 0.0), r_big, 0.0, PI),
]);
let r = contour_integral(|z| (z * z + 1.0).inv(), &semicircle, 1e-12).unwrap();
println!("closed semicircle: {:.12} (π = {PI:.12})", r.value.re);
// Cauchy's formula for derivatives: the 5th derivative of e^z at 0 is 1.
let d = cauchy_derivative(|z| z.exp(), C64::new(0.0, 0.0), 5, 2.0, 1e-13).unwrap();
println!("f⁽⁵⁾(0) for f = eᶻ: {d:.14}");
// Winding numbers of a polygon.
let triangle = [C64::new(0.0, 0.0), C64::new(2.0, 0.0), C64::new(1.0, 2.0)];
println!("winding number around (1, 0.5): {:?}, around (3, 3): {:?}", winding_number(&triangle, C64::new(1.0, 0.5)), winding_number(&triangle, C64::new(3.0, 3.0)));
}
Strengths
- Turns hard real integrals, high derivatives and zero-counting into well-conditioned integrals.
- Paths of lines, arcs and arbitrary curves, with an error estimate.
- Exact winding numbers for polygons.
Weaknesses
- The path must keep away from singularities: a contour through or very close to a pole fails or needs very many evaluations.
- For full circles the adaptive rule is several times slower than the trapezoid rule.
- High derivatives need a well-chosen radius; too small or too large loses accuracy quickly.
Exercises
- Evaluate by integrating around a closed semicircle, and explain why is used rather than .
- Implement the trapezoid rule on a circle and use it to compute the first 20 Taylor coefficients of at . What are they? On which circles does the computation converge?
- Use
cauchy_derivativeto compute the 20th derivative of at . The poles nearest to 0 are at : how does this limit the radius, and the accuracy? - Counting zeros. The argument principle says is the number of zeros minus the number of poles of inside the contour. Use it to count the zeros of inside , and check against the roots.
- Show that and confirm it numerically. Why does this not contradict Cauchy’s theorem?
Hints and answers
- Close the contour with a large upper semicircle. decays in the upper half-plane, so the arc contributes nothing, whereas grows like there. The only pole inside is , with residue , so the integral is , whose real part is the cosine integral.
- The coefficients are the Fibonacci numbers . The series converges inside the circle through the nearest pole, at (the other pole is at ), so circles of radius below work.
- Since is odd, its 20th derivative at 0 is exactly , so this tests how close to zero the computed value comes. The contour radius must stay below . Cauchy’s formula for the 20th derivative divides by , so a small radius amplifies rounding error by ; a radius close to is best.
- on , so by Rouché’s theorem has the same number of zeros inside as , namely 1. The integral should come out as (to rounding); the real root near is the one inside.
- On , , so . Cauchy’s theorem needs an analytic integrand and is not analytic (it fails the Cauchy-Riemann equations). Green’s theorem gives .
Further reading
- A.-L. Cauchy, Mémoire sur les intégrales définies prises entre des limites imaginaires, Paris, 1825.
- J. N. Lyness and C. B. Moler, “Numerical differentiation of analytic functions”, SIAM Journal on Numerical Analysis 4 (1967) 202–210.
- J. N. Lyness and L. M. Delves, “On numerical contour integration round a closed contour”, Mathematics of Computation 21 (1967) 561–577.
- F. Bornemann, “Accuracy and stability of computing high-order derivatives of analytic functions by Cauchy integrals”, Foundations of Computational Mathematics 11 (2011) 1–63.
- L. N. Trefethen and J. A. C. Weideman, “The exponentially convergent trapezoidal rule”, SIAM Review 56 (2014) 385–458, sections on contour integrals.
- T. Needham, Visual Complex Analysis, Oxford University Press, 1997. A geometric introduction to the theory used here.