Skip to content

Fix binomial_distribution overflow at 171 trials - #15659

Open
trleo wants to merge 1 commit into
TheAlgorithms:masterfrom
trleo:fix/binomial-distribution-overflow
Open

trleo wants to merge 1 commit into
TheAlgorithms:masterfrom
trleo:fix/binomial-distribution-overflow

Conversation

@trleo

@trleo trleo commented Oct 28, 2026

Copy link
Copy Markdown

Describe your change

  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests?

Fixes #15656. binomial_distribution converted factorial(trials) to float before dividing, so binomial_distribution(85, 171, 0.5) raised OverflowError: int too large to convert to float. This change uses math.comb(trials, successes), which is exact and avoids the huge float conversion, and adds a regression doctest for (85, 171, 0.5) giving 0.060749764626165485. Existing guards and other doctests are unchanged.

Tested on Linux: python -m doctest maths/binomial_distribution.py passes 3 tests, ruff check and ruff format pass. Ruff/pytest via uvx were not available in this environment, so CI should confirm those.

Note: for much larger inputs the p**k terms can still underflow; this fixes the reported case.

Checklist

  • I have read CONTRIBUTING.md
  • This pull request is all my own work
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file.
  • All function parameters and return values are annotated with type hints
  • All functions have doctests that pass.

@algorithms-keeper algorithms-keeper Bot added awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files labels Oct 28, 2026

This branch has not been deployed

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

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

binomial_distribution overflows at 171 trials even when the result is representable

1 participant