Bug report
Bug description:
poc:
""" PoC: binomialvariate crash caused by random() returning 0.0. Run: python bug_demo.py """ from math import log2, floor def simulate_crash(c, n): """Simulate the buggy BG branch with random() hardcoded to 0.0. Records the iteration count at which the crash occurs.""" x = y = 0 iter_count = 0 while True: iter_count += 1 rand_val = 0.0 # simulate the rare event of hitting exactly 0.0 try: log_rand = log2(rand_val) except ValueError as e: print(f"Crashed at iteration {iter_count}: {e}") return None, iter_count y += floor(log_rand / c) + 1 if y > n: return x, iter_count x += 1 if __name__ == "__main__": c = log2(0.5) # -1.0 result, count = simulate_crash(c, n=1) if result is None: print(f"Program crashed after {count} iteration(s) (crashed immediately).") else: print(f"Result {result}, loop ran {count} iteration(s)")
Actual behavior:
· When random() returns exactly 0.0 (which is within the documented range [0.0, 1.0)), _log2(0.0) raises a ValueError: math domain error, crashing the program.
Expected behavior:
· The function should never crash on a valid random value.
· The returned values should accurately follow the binomial distribution with parameters n and p.
CPython versions tested on:
CPython main branch
Operating systems tested on:
Other, Linux
Linked PRs
- gh-149221:Fix binomialvariate Function for random module #149222
- gh-149221: Handle corner case in random.binomialvariate() #149266
- [3.14]gh-149221:Fix binomialvariate Function for random module #149276
- gh-149221: Minor comment edit #149278
- [3.13] gh-149221:Fix binomialvariate Function for random module #149279
- [3.14] gh-149221: Sync random.py with main branch #149288
- [3.14] gh-149221: Add missing
test_binomialvariate_log_zero#154879