FrankenNumPy

Docs/Numerics

Numerical Stability and Precision Notes

"Same answer, mostly" is not enough. A library that aspires to bit-exact or behaviorally-equivalent output has to face concrete numerical-analysis choices.

Summation strategy. Reductions use a two-tier compensated-summation policy (reduce_sum_values in crates/fnp-ufunc/src/lib.rs):

  • Arrays with ≤ 1,000,000 finite values (or any non-finite value at all) use a straight linear sum. At those sizes naive accumulation has bounded error and the branch prediction wins on cost.
  • Arrays larger than COMPENSATED_SUM_MIN_LEN = 1,000,000 switch to Neumaier-compensated sum, a Kahan variant that handles the |value| > |running sum| case correctly. Error stays at O(ε) per element instead of O(n·ε), which matters at the sizes where naive summation drifts.

The same selector is used for strided axis reductions (reduce_sum_strided), so axis-wise sums on large contiguous chunks get the same compensation treatment. The contiguous-reduction fast path that drove the ~56% p50 latency improvement landed in commit d9cfe90 (2026-02-13); the proof bundle is under artifacts/optimization/.

Polynomial evaluation. Power-series, Chebyshev, Legendre, Hermite, and Laguerre evaluations all use Horner's method (or the Clenshaw recurrence for orthogonal bases). This minimizes multiplications and keeps the floating-point error proportional to the polynomial degree rather than to repeated powers of x.

Catastrophic cancellation. Where NumPy uses identities to dodge cancellation (e.g. log1p(x) ≈ x - x²/2 + x³/3 for small x, computed via the FMA-style libc routine), we use the same f64::ln_1p, f64::exp_m1, etc.; the standard-library backers are themselves engineered to avoid cancellation. nextafter, spacing, and signbit route through libc-equivalent paths so denormals and signed zero are handled identically.

NaN propagation. A dedicated oracle-test sweep verifies that NaN propagates through every reduction, every sort, every percentile/median/quantile, every cumulative operation, and every set operation; tests live in crates/fnp-ufunc/tests/ and the metamorphic suite at crates/fnp-ufunc/tests/metamorphic_math.rs (e.g. partition_contract_binary_mul_preserves_nan_and_signed_zero_bits, parallel_opt_in_sum_axis_matches_serial_for_nan_signed_zero_and_empty_axes). Where NumPy's documented behavior is "NaN sorts to the end," we use the explicit nan_last_cmp ordering rather than relying on partial_cmp().unwrap_or(Equal) (which is a silent bug).

Signed zero. maximum(-0.0, 0.0), heaviside(0.0, ...), floor_divide of negative operands, remainder, clip, divmod, and cummin/cummax all preserve signed-zero semantics matching NumPy. These are explicit fixture cases in fnp-ufunc/tests.

Denormals. No flush-to-zero. Subnormal inputs to ufuncs produce subnormal outputs, matching NumPy with denormals enabled (which is the default on most platforms). Fuzzer seeds include subnormal corners (smallest positive subnormal, largest subnormal, transition to normal) under crates/fnp-dtype/fuzz/corpus.

Linear algebra tolerances. Singularity checks for lu_factor, cholesky, and triangular solve use exact zero (not an epsilon threshold), matching NumPy. Rank determination uses the largest singular value times machine epsilon times max(m, n), the standard SVD-based numerical-rank criterion. Conditioning is computed exactly through the SVD; no rank-1 approximations.

FFT precision. Both Cooley–Tukey (power-of-two) and Bluestein chirp-Z (arbitrary length) implementations use f64 throughout the recursion and synthesis steps. Twiddle and chirp factors are computed directly from angle.cos() / angle.sin() in double precision; no single-precision table tricks. The Bluestein chirp uses exp(±i·π·k² / n) derived inline. An fft_mul helper protects against the case where a near-zero twiddle (e.g. cos(π/2) evaluating to ~6e-17 instead of 0) multiplies an Inf or NaN input: the result is forced to 0.0 when the twiddle is within 1e-14 of zero and the other operand is non-finite. This matches NumPy's behavior at multiples of π/2.

RNG bit-exactness vs distribution shape. The bit-exact contract holds for the core integer-emission stream (PCG64DXSM, MT19937, Philox, SFC64) and for the eight algorithm families ported verbatim from NumPy's C source (BTPE binomial, HRUA hypergeometric, PTRS Poisson, Marsaglia–Tsang gamma, Ziggurat normal/exponential, Lemire bounded ints, Fisher–Yates shuffle, Zipf rejection). Distribution methods built on top inherit bit-exactness when their algebra is identical.


This section in the README on GitHub