Skip to content

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

Closed

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

  1. added
    type-bugAn unexpected behavior, bug, or error
    on Jul 18, 2026
  2. added 3 commits that reference this issue on Jul 18, 2026
  3. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Jul 18, 2026
  4. added a commit that references this issue on Jul 18, 2026
  5. added a commit that references this issue on Jul 19, 2026
  6. serhiy-storchaka commented on Jul 19, 2026

    @serhiy-storchaka
    Member

    Thank you for your contribution @lkk7.

  7. added
    3.13only security fixes
    3.14bugs and security fixes
    3.15bugs and security fixes
    3.16new features, bugs and security fixes
    on Jul 19, 2026
  8. added 3 commits that reference this issue on Jul 19, 2026
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.13only security fixes3.14bugs and security fixes3.15bugs 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