Dynamic Gauss-Legendre numerical integration in C#: computing nodes and weights on the fly without overflow
A C# walkthrough of Gauss-Legendre quadrature that computes Legendre polynomial roots and weights at runtime instead of shipping precomputed tables. Bonnet's recurrence keeps the polynomial evaluation stable past degree 15, and Newton's method finds each root to about 1e-10 in a few iterations.
Key points
- Polynomial values come from Bonnet's three-term recurrence, so no coefficient table is built and degrees above 15 no longer overflow.
- Roots start from cos(π(4(n−i)−1)/(4n+2)) and are refined by Newton's method to about 1e-12 in the combined node routine.
- Each weight is 2/((1−x²)·P′ₙ(x)²); the derivative from the final Newton step is reused, so no second pass is needed.
- The quadrature maps nodes from [−1, 1] to the caller's interval and defaults to 32 nodes, but accepts any order at runtime.
- Early exit condition compares successive iterates against a tolerance instead of a fixed iteration count, keeping node search short.
- Author's comparison: 16 Gauss-Legendre nodes gave 12 correct decimals, while Simpson's rule needed 1000 nodes for 5.
Gauss-Legendre quadrature needs far fewer evaluations than fixed-step rules such as Simpson's, but it depends on the roots of Legendre polynomials and on matching weights. Building those polynomials from their binomial expansion overflows once the degree passes 15, so the author instead evaluates them with Bonnet's three-term recurrence and takes the derivative from a closed formula, including the special cases at x = ±1 where the denominator collapses.
Each root is located by Newton's method from the start value cos(π(4(n−i)−1)/(4n+2)), reaching roughly 1e-10 in a handful of iterations; the weight follows as 2/((1−x²)·P′ₙ(x)²). A quadrature routine shifts the nodes onto the requested interval and defaults to 32 points. In the author's benchmark, 16 points reproduced 12 decimals while Simpson's rule still missed them at 1000.
Real-world use
- An engineering or physics tool that integrates smooth functions such as work, flux or area to many digits inside a loop.
- A simulation library that needs a quadrature rule of arbitrary order without embedding precomputed node tables.
- Unit tests that validate an adaptive integrator against a high-order Gauss-Legendre reference value.
- A statistics utility computing expectations over continuous distributions where polynomial integrands need few evaluations.
Why it matters
You get a reusable, table-free quadrature routine whose order you choose at runtime, so smooth integrands reach close to machine precision with a fraction of the evaluations fixed-step methods spend.