Expand description
Loader’s saddle-point pieces for densities of the shape $x^k e^{-x}/\Gamma(k+1)$.
The Poisson mass $e^{-\lambda}\lambda^k/k!$, the Gamma density, and the seed of the
orthonormal Laguerre functions are all this shape, and the obvious spelling
exp(k ln lambda - lgamma(k+1) - lambda) computes an O(1) answer as the exponential
of a difference of large terms: half an ulp of lgamma(k+1) = O(k ln k) becomes that
many ulp of the result. Loader (2000, “Fast and accurate computation of binomial
probabilities”, the form R’s dpois uses) rewrites it as
\frac{\lambda^k e^{-\lambda}}{k!} = \frac{e^{-\mathrm{stirlerr}(k) - \mathrm{bd0}(k, \lambda)}}{\sqrt{2\pi k}}with the two pieces below, both small where the density is not negligible, so the exponential amplifies nothing.
Constants§
- STIRLERR_
MIN - Below this the Stirling series in
stirlerris not accurate to binary64 at any depth (it is asymptotic, and the smallest term atn = 9is under1e-18, atn = 6it is1e-14). Callers handlen < STIRLERR_MINsome other way: a table for integers, orGamma(n+1)directly, which is cheap and well conditioned at small argument.
Functions§
- bd0_
series - The binomial/Poisson deviance
bd0(k, lambda) = k ln(k/lambda) + lambda - k >= 0in its peak form:(k - lambda) v + 2k sum_{j>=1} v^{2j+1}/(2j+1)forv = (k - lambda)/(k + lambda)(fromln((1+v)/(1-v)) = 2 atanh v),bd0_termsterms, full precision inside|v| < 1/5. Away from the peak the direct form is fine andpmf_partsuses it (folded with the rest of the exponent); this is only the part that needs care.diffandvare passed in because callers have them. - bd0_
terms - Terms of the odd series in [
bd0] by tier, inside|v| < 1/5. - exp_sum
exp(base + rest_hi + rest_lo)wherebaseis a large exact-ish number (-lambda,x/4) and therestpair is small: TwoSum recovers the rounding of the sum, ande^{s + lo} = e^s (1 + lo)to first order. Without it the sum rounds to half an ulp ofbase, which the exponential turns into hundreds of ulp.- pmf_
parts - The shared core of every
$x^k e^{-x}/\Gamma(k+1)$shape here: the Poisson mass, its log, and the Laguerre-function seed. Returns(rest_hi, rest_lo, large, prod, n)such that - poisson_
pmf - The Poisson mass
$e^{-\lambda}\lambda^k/k!$at realk >= 0,lambda >= 0(LOG = false), or its log (LOG = true), throughpmf_parts. Realkbecause the Gamma density is the same function (dgamma(x; a) = pmf(a - 1; x)fora >= 1). - stirlerr
- Stirling’s error
$\mathrm{stirlerr}(n) = \ln n! - \left[(n + \tfrac12)\ln n - n + \tfrac12 \ln 2\pi\right]$, forn >= STIRLERR_MIN, by the Bernoulli series - stirlerr_
terms - Terms of the
1/n^2series instirlerrby tier, atn >= STIRLERR_MIN. The dropped term bounds the absolute error, which is the relative error of whatever density it feeds: 9 terms is1e-18, 6 is2.5e-15(a measured 5 ulp atn = 9, soAveragekeeps all 9, the three FMAs being nothing), 5 is1e-13, and the single1/(12n)term is3.8e-6.Worstforgoes the series and keeps just that.