Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 3 additions & 1 deletion Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,9 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
raise ValueError('The number of weights does not match the population')
bisect = _bisect.bisect
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 -------------------

Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,14 @@ def test_choices(self):
with self.assertRaises(IndexError):
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):
# 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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve random.choices() to handle subnormal input weights that could
occasionally trigger an IndexError.