Skip to content

random.binomialvariate() can raise ZeroDivisionError when random() returns 0.0 #154001

Description

@lkk7

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

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13bugs and security fixes3.14bugs and security fixes3.15pre-release feature fixes, bugs and security fixes3.16new features, bugs and security fixesstdlibStandard 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