Skip to content

random module binomialvariate function returns wrong results #149221

@lighting9999

Description

@lighting9999

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

Metadata

Metadata

Assignees

Labels

stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions