Skip to content

perf: sample Binomial via BINV/BTPE instead of n Bernoulli trials#409

Open
agene0001 wants to merge 2 commits into
statrs-dev:mainfrom
agene0001:fix/183-btpe-sampling
Open

perf: sample Binomial via BINV/BTPE instead of n Bernoulli trials#409
agene0001 wants to merge 2 commits into
statrs-dev:mainfrom
agene0001:fix/183-btpe-sampling

Conversation

@agene0001

Copy link
Copy Markdown

Binomial::sample ran one Bernoulli trial per trial, so a single draw was O(n). The case reported in #183 (5 categories, n = 100 000, sampled via Multinomial) took 22.4 ms per 100 draws here; numpy was reported ~400x faster.

This replaces it with Kachitvichyanukul & Schmeiser (1988): BINV inversion for n·min(p,1−p) < 10, BTPE rejection otherwise, exact shortcuts for p ∈ {0, 1}, and a Poisson-limit path when 1 − p rounds to 1.0.

before after
Binomial(0.4, 1_000).sample() 3.6 µs 56 ns
Binomial(0.4, 100_000).sample() 361 µs 39 ns
Binomial(0.4, 1e9).sample() ~3.6 s 39 ns
Multinomial(5 cats, n=1e5) ×100 22.4 ms 22.8 µs (981x)

Multinomial benefits automatically since it draws conditioned binomials per category.

The implementation is adapted from rand_distr (MIT/Apache-2.0, attributed in-source). One detail worth review attention: the final acceptance test uses the Stirling-series signs from GSL, which differ from the published paper and were verified by one of the algorithm's original designers (see the in-source comment).

Correctness: chi-square goodness-of-fit against the exact pmf over five parameter sets covering every code path (BINV, BTPE, both flipped variants), with expected-count pooling and a 6σ threshold on fixed seeds — deterministic, so a failure means a real defect, not chance. Plus moment tests for n = 1e9 and the Poisson-limit path, and degenerate-parameter tests. Relates to the sampling-verification wish list in #288.

Closes #183

🤖 Generated with Claude Code

agene0001 and others added 2 commits July 26, 2026 09:55
`Binomial::sample` ran one Bernoulli trial per trial, so a single draw was
O(n). The reported case in statrs-dev#183 - 5 categories, n = 100_000, 100 samples via
`Multinomial` - took 22.4 ms; numpy was measured at ~400x faster.

Replaces it with Kachitvichyanukul & Schmeiser (1988): BINV inversion for
`n * min(p, 1-p) < 10`, BTPE rejection from a triangle/parallelogram/two
exponential tails envelope otherwise, plus exact shortcuts for p in {0, 1} and a
Poisson-limit path when `1 - p` rounds to 1.

    Binomial(0.4, 1_000).sample()          3.6 us -> 56 ns
    Binomial(0.4, 100_000).sample()         361 us -> 39 ns
    Binomial(0.4, 1e9).sample()           ~3.6 s  -> 39 ns
    Multinomial(5 cats, n=1e5) x100        22.4 ms -> 22.8 us   (981x)

`Multinomial` benefits automatically, since it draws conditioned binomials per
category - which is what the issue asked for.

The implementation is adapted from `rand_distr` (MIT/Apache-2.0, attributed
in-source). That matters for one detail: the final acceptance test uses the
Stirling-series signs from GSL, which differ from the published paper and were
verified by one of the algorithm's original designers.

Correctness is checked by a chi-square goodness-of-fit test against the exact
pmf over five parameter sets covering every code path (BINV, BTPE, and both
flipped variants), with expected-count pooling and a 6-sigma threshold on fixed
seeds - so it is deterministic and a failure means a real defect. Plus moment
tests for n = 1e9 and the Poisson-limit path, and degenerate-parameter tests.

Closes statrs-dev#183
The test sizes its histogram and its pooled cells from n and p at run time,
so it needs `Vec`, which does not exist under `--no-default-features`: the
crate is `no_std` without `alloc`. It was gated on `rand` alone, so
`--no-default-features --features rand` failed to compile the test binary.

Gated on `std` as well rather than rewritten around fixed-size arrays, since
a goodness-of-fit test with dynamic binning genuinely wants allocation. The
sampler still has no-std coverage from
`test_sample_extreme_parameters_moments`, which uses no collections.

CI did not catch this because the test job runs only default features, and
the feature-powerset job passes `--no-dev-deps`, so test code is never
compiled without std.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@codecov

codecov Bot commented Jul 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.97980% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.82%. Comparing base (1029458) to head (aa03f2d).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
src/distribution/binomial.rs 97.97% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #409      +/-   ##
==========================================
+ Coverage   94.77%   94.82%   +0.04%     
==========================================
  Files          61       61              
  Lines       13402    13596     +194     
==========================================
+ Hits        12702    12892     +190     
- Misses        700      704       +4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

if q == 1.0 {
// p is below ~2^-54 (and not flipped, since p <= 0.5): the
// distribution is indistinguishable from Poisson(n * p) to O(p)
return super::poisson::sample_unchecked(rng, n as f64 * p) as u64;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs to flip


let mut counts = vec![0u64; (hi - lo + 1) as usize];
let mut outside = 0u64;
for _ in 0..SAMPLES {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would you not be able to build atop stats_tests::chisquare for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Multinomial sampling is very slow

2 participants