Skip to content

random.betavariate hangs for very large finite positive shape parameters #158744

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: Random.betavariate docstring: "Conditions on the parameters are alpha > 0 and beta > 0." and "E[X] = alpha / (alpha + beta)". Mathematically, equal positive parameters give an expected value of 0.5.

Expected: Sampling terminates and returns beta-distributed values concentrated near 0.5.

Actual: The subprocess timed out after one second; no samples or sample mean were obtained.

import random, math, subprocess, sys, json

a = b = 9e307
seed, n = 0, 128
inp = dict(alpha=a, beta=b, seed=seed, samples=n)
if not (math.isfinite(a) and math.isfinite(b) and a > 0 and b > 0):
    print("REFUTATION REJECTED:", inp, "invalid parameters")
else:
    expected = 1 / (1 + b / a)  # Avoid overflow in alpha + beta.
    code = (
        f"import random,json; r=random.Random({seed}); "
        f"print(json.dumps([r.betavariate({a!r},{b!r}) for _ in range({n})]))"
    )
    try:
        p = subprocess.run(
            [sys.executable, "-c", code],
            capture_output=True, text=True, timeout=1
        )
        if p.returncode:
            print("REFUTATION REJECTED:", inp, "test failed:", p.stderr.strip())
        else:
            xs = json.loads(p.stdout)
            actual = dict(mean=math.fsum(xs) / n, all_zero=all(x == 0 for x in xs))
            broken = actual["all_zero"] or any(not 0 <= x <= 1 for x in xs)
            print("REFUTATION CONFIRMED:" if broken else "REFUTATION REJECTED:",
                  inp, "actual:", actual, "expected:", expected,
                  *([] if broken else ["no demonstrated violation"]))
    except subprocess.TimeoutExpired:
        print("REFUTATION CONFIRMED:", inp,
              "actual:", {"timeout_seconds": 1}, "expected:", expected)

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

REFUTATION CONFIRMED: {'alpha': 9e+307, 'beta': 9e+307, 'seed': 0, 'samples': 128} actual: {'timeout_seconds': 1} expected: 0.5

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-101511-c1

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