Skip to content

random.binomialvariate returns deterministic zero for small positive p with n*p=1 #158747

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: Random.binomialvariate docstring: "The mean (expected value) and variance of the random variable are: E[X] = n * p"; it also specifies "P(X == k) = math.comb(n, k) * p ** k * (1 - p) ** (n - k)".

Expected: A nondegenerate binomial sample with mean 1; the probability of zero is approximately exp(-1), not 1.

Actual: Returns 0 without consuming randomness for n=255 and p=2-55.

import math
import random
from fractions import Fraction

n, p = 2**55, 2**-55
if not (isinstance(n, int) and n >= 0 and math.isfinite(p) and 0 <= p <= 1):
    print("REFUTATION REJECTED:", "invalid input")
else:
    class TrackedRandom(random.Random):
        calls = 0

        def random(self):
            self.calls += 1
            return super().random()

        def getrandbits(self, k):
            self.calls += 1
            return super().getrandbits(k)

    rng = TrackedRandom(0)
    expected = n * Fraction(p)
    actual = rng.binomialvariate(n, p)
    if actual != expected and rng.calls == 0:
        print("REFUTATION CONFIRMED:", (n, p), "actual =", actual,
              "expected mean =", expected, "(no randomness consumed)")
    else:
        print("REFUTATION REJECTED:", "deterministic wrong result not reproduced",
              (n, p), "actual =", actual, "expected mean =", expected)

Output on Python 3.14.6 (Windows-11-10.0.26220-SP0), standard library random:

REFUTATION CONFIRMED: (36028797018963968, 2.7755575615628914e-17) actual = 0 expected mean = 1 (no randomness consumed)

This report was found and written by an automated property-testing tool I run (bugforge). The reproducer above was executed and its output is pasted unedited; no person reviewed the report before it was filed. The search script is in https://github.com/augusto-rehfeldt/bugforge-results/tree/main/random-20261003-142339-c4

CPython versions tested on:

3.14

Operating systems tested on:

Windows

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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions