Skip to content

Commit 494989d

Browse files
[3.14] gh-149221: Sync random.py with main branch (#149288)
* [3.14] fix trailing whitespace * sync with main
1 parent 644f94c commit 494989d

1 file changed

Lines changed: 9 additions & 9 deletions

File tree

Lib/random.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -836,21 +836,20 @@ def binomialvariate(self, n=1, p=0.5):
836836
if not c:
837837
return x
838838
while True:
839-
try:
839+
try:
840840
y += _floor(_log2(random()) / c) + 1
841-
# The random() function can return 0.0, which causes log2(0.0) to raise a ValueError.
842-
# See https://github.com/python/cpython/issue/149221
843841
except ValueError:
844-
continue
842+
# Reject case where random() returned 0.0
843+
continue
845844
if y > n:
846845
return x
847846
x += 1
848847

849848
# BTRS: Transformed rejection with squeeze method by Wolfgang Hörmann
850849
# https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.47.8407&rep=rep1&type=pdf
851850
assert n*p >= 10.0 and p <= 0.5
852-
setup_complete = False
853851

852+
setup_complete = False
854853
spq = _sqrt(n * p * (1.0 - p)) # Standard deviation of the distribution
855854
b = 1.15 + 2.53 * spq
856855
a = -0.0873 + 0.0248 * b + 0.01 * p
@@ -865,22 +864,23 @@ def binomialvariate(self, n=1, p=0.5):
865864
k = _floor((2.0 * a / us + b) * u + c)
866865
if k < 0 or k > n:
867866
continue
867+
v = random()
868868

869869
# The early-out "squeeze" test substantially reduces
870870
# the number of acceptance condition evaluations.
871-
v = random()
872871
if us >= 0.07 and v <= vr:
873872
return k
874873

875-
# Acceptance-rejection test.
876-
# Note, the original paper erroneously omits the call to log(v)
877-
# when comparing to the log of the rescaled binomial distribution.
878874
if not setup_complete:
879875
alpha = (2.83 + 5.1 / b) * spq
880876
lpq = _log(p / (1.0 - p))
881877
m = _floor((n + 1) * p) # Mode of the distribution
882878
h = _lgamma(m + 1) + _lgamma(n - m + 1)
883879
setup_complete = True # Only needs to be done once
880+
881+
# Acceptance-rejection test.
882+
# Note, the original paper erroneously omits the call to log(v)
883+
# when comparing to the log of the rescaled binomial distribution.
884884
v *= alpha / (a / (us * us) + b)
885885
if _log(v) <= h - _lgamma(k + 1) - _lgamma(n - k + 1) + (k - m) * lpq:
886886
return k

0 commit comments

Comments
 (0)