perf: sample Binomial via BINV/BTPE instead of n Bernoulli trials#409
Open
agene0001 wants to merge 2 commits into
Open
perf: sample Binomial via BINV/BTPE instead of n Bernoulli trials#409agene0001 wants to merge 2 commits into
agene0001 wants to merge 2 commits into
Conversation
`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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
YeungOnion
reviewed
Jul 27, 2026
| 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; |
YeungOnion
reviewed
Jul 27, 2026
|
|
||
| let mut counts = vec![0u64; (hi - lo + 1) as usize]; | ||
| let mut outside = 0u64; | ||
| for _ in 0..SAMPLES { |
Contributor
There was a problem hiding this comment.
would you not be able to build atop stats_tests::chisquare for this?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Binomial::sampleran one Bernoulli trial per trial, so a single draw was O(n). The case reported in #183 (5 categories, n = 100 000, sampled viaMultinomial) 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 when1 − prounds to 1.0.Binomial(0.4, 1_000).sample()Binomial(0.4, 100_000).sample()Binomial(0.4, 1e9).sample()Multinomial(5 cats, n=1e5)×100Multinomialbenefits 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