Skip to content
fn

normal_pdf_f32

float normal_pdf_f32(float x)

The standard normal density exp(-x^2 / 2) / sqrt(2 pi), in float32 arithmetic, branch-free so the loop around it vectorises four lanes wide.

exp(-s) = 2^n * e^r, s = x^2 / 2, n = -round(s / ln 2), |r| <= ln2 / 2

s is carried as two floats: s = h * a rounded (h = a / 2) and, negated, what that rounding dropped, fma(-h, a, s), exact. The low part joins the reduced argument together with the low half of n * ln 2 (Cody-Waite: n * ln2_hi is exact and s + n * ln2_hi cancels exactly), so r is rounded once, at its own size. e^r is 1 + r * P(r), P of degree 5 fitted to 3e-9.

2^n is added straight into the exponent field of e^r. Adding 1.5 * 2^23

  • 64 rounds -s / ln 2 to an integer and leaves n + 64 in the low bits, so the scale is a shift and an integer add, and e^r * 2^(n + 64) is a normal float for every n the clamp allows. The 2^-64 is folded into the 1 / sqrt(2 pi) of the last multiply, so a density that underflows (|x| > 13.39) is rounded once, into the subnormals, instead of being rounded there and then multiplied again.

|x| is clamped to 14.5, past the point where the density rounds to zero (14.36), which keeps x^2 and n in range for any input: +-inf and NaN give 0, as huge finite inputs do.