Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 73ced7e

Browse files
committed
Correct long standing bugs in the methods for random distributions.
The range of u=random() is [0,1), so log(u) and 1/x can fail. Fix by setting u=1-random() or by reselecting for a usable value. Will backport.
1 parent 3a57d9d commit 73ced7e

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

Lib/random.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ def normalvariate(self, mu, sigma):
282282
random = self.random
283283
while True:
284284
u1 = random()
285-
u2 = random()
285+
u2 = 1.0 - random()
286286
z = NV_MAGICCONST*(u1-0.5)/u2
287287
zz = z*z/4.0
288288
if zz <= -_log(u2):
@@ -422,7 +422,9 @@ def gammavariate(self, alpha, beta):
422422

423423
while True:
424424
u1 = random()
425-
u2 = random()
425+
if not 1e-7 < u1 < .9999999:
426+
continue
427+
u2 = 1.0 - random()
426428
v = _log(u1/(1.0-u1))/ainv
427429
x = alpha*_exp(v)
428430
z = u1*u1*u2
@@ -554,7 +556,7 @@ def paretovariate(self, alpha):
554556
"""Pareto distribution. alpha is the shape parameter."""
555557
# Jain, pg. 495
556558

557-
u = self.random()
559+
u = 1.0 - self.random()
558560
return 1.0 / pow(u, 1.0/alpha)
559561

560562
## -------------------- Weibull --------------------
@@ -567,7 +569,7 @@ def weibullvariate(self, alpha, beta):
567569
"""
568570
# Jain, pg. 499; bug fix courtesy Bill Arms
569571

570-
u = self.random()
572+
u = 1.0 - self.random()
571573
return alpha * pow(-_log(u), 1.0/beta)
572574

573575
## -------------------- Wichmann-Hill -------------------

0 commit comments

Comments
 (0)