8000 GH-81620: Add random.binomialvariate() by rhettinger · Pull Request #94719 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

GH-81620: Add random.binomialvariate() #94719

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Jul 13, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
More elaborate comments
  • Loading branch information
rhettinger committed Jul 9, 2022
commit c9d3ca851d900863e337d1a3757cbe939f7eecab
19 changes: 13 additions & 6 deletions Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,7 +737,9 @@ def binomialvariate(self, n=1, p=0.5):
"""Binomial random variable.

Gives the number of successes for *n* Bernoulli trials
with the probability of success in each trial being *p*.
with the probability of success in each trial being *p*:

sum(random() < p for i in range(n))

Returns an integer in the range: 0 <= X <= n

Expand Down Expand Up @@ -802,16 +804,21 @@ def binomialvariate(self, n=1, p=0.5):
us = 0.5 - _fabs(u)
k = _floor((2.0 * a / us + b) * u + c)

# Step 2: Skip over invalid k due to numeric issues.
# Then make the bounding box test.
# Step 2: Skip over invalid k arising due to numeric issues.
if k < 0 or k > n:
continue

# This early-out "squeeze" test substantially reduces the
# number of acceptance condition evaluations. Checks to see
# whether *us* and *vr* lie in the large rectangle between
# the u-axis and the curve.
if us >= 0.07 and v <= vr:
return k

# Step 3.1: Acceptance-rejection test
# Original paper errorneously omits the call to log(v) which
# is needed because we're comparing to the log factorials.
# Step 3.1: Acceptance-rejection test.
# N.B. The original paper errorneously omits the call to
# log(v) which is needed because we're comparing to the log
# of the rescaled binomial distribution.
v *= alpha / (a / (us * us) + b)
if _log(v) <= h - _logfact(k) - _logfact(n - k) + (k - m) * lpq:
return k
Expand Down
0