Kaydet (Commit) 0eaf7b97 authored tarafından Miss Islington (bot)'s avatar Miss Islington (bot) Kaydeden (comit) Raymond Hettinger

bpo-24567: Random subnormal.diff (GH-7954) (GH-7955)

Handle subnormal weights for choices()
(cherry picked from commit ddf71719)
Co-authored-by: 's avatarRaymond Hettinger <rhettinger@users.noreply.github.com>
üst ca97b64a
...@@ -361,7 +361,9 @@ class Random(_random.Random): ...@@ -361,7 +361,9 @@ class Random(_random.Random):
raise ValueError('The number of weights does not match the population') raise ValueError('The number of weights does not match the population')
bisect = _bisect.bisect bisect = _bisect.bisect
total = cum_weights[-1] total = cum_weights[-1]
return [population[bisect(cum_weights, random() * total)] for i in range(k)] hi = len(cum_weights) - 1
return [population[bisect(cum_weights, random() * total, 0, hi)]
for i in range(k)]
## -------------------- real-valued distributions ------------------- ## -------------------- real-valued distributions -------------------
......
...@@ -227,6 +227,14 @@ class TestBasicOps: ...@@ -227,6 +227,14 @@ class TestBasicOps:
with self.assertRaises(IndexError): with self.assertRaises(IndexError):
choices([], cum_weights=[], k=5) choices([], cum_weights=[], k=5)
def test_choices_subnormal(self):
# Subnormal weights would occassionally trigger an IndexError
# in choices() when the value returned by random() was large
# enough to make `random() * total` round up to the total.
# See https://bugs.python.org/msg275594 for more detail.
choices = self.gen.choices
choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
def test_gauss(self): def test_gauss(self):
# Ensure that the seed() method initializes all the hidden state. In # Ensure that the seed() method initializes all the hidden state. In
# particular, through 2.2.1 it failed to reset a piece of state used # particular, through 2.2.1 it failed to reset a piece of state used
......
Improve random.choices() to handle subnormal input weights that could
occasionally trigger an IndexError.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment