Bug report
Bug description:
random.binomialvariate() can raise ZeroDivisionError when random() returns 0.0 in one of the paths.
# Lib/random.py u = random() u -= 0.5 us = 0.5 - _fabs(u) k = _floor((2.0 * a / us + b) * u + c) # <-- division by `us` which can be zero
Repro with a mock that forces random() to return zero:
import random from unittest.mock import patch with patch.object(random.Random, "random", side_effect=[0.0, 0.5, 0.5]): random.binomialvariate(100, 0.25) # k = _floor((2.0 * a / us + b) * u + c) # ~~~~~~~~^~~~ # ZeroDivisionError: division by zero
From what I've seen, it looks like the chance of random returning zero is about 1 in 2^53... But still, zero is a valid result and custom generators may return it more often.
CPython versions tested on:
3.12, 3.13, 3.14, 3.15
Operating systems tested on:
macOS
Linked PRs
- gh-154001: Avoid division by zero in
binomialvariate#154004 - [3.15] gh-154001: Avoid division by zero in binomialvariate (GH-154004) #154050
- [3.14] gh-154001: Avoid division by zero in binomialvariate (GH-154004) #154051
- [3.13] gh-154001: Avoid division by zero in binomialvariate (GH-154004) #154052