]> granicus.if.org Git - python/commitdiff
bpo-24567: Random subnormal.diff (#7954)
authorRaymond Hettinger <rhettinger@users.noreply.github.com>
Wed, 27 Jun 2018 08:08:31 +0000 (01:08 -0700)
committerGitHub <noreply@github.com>
Wed, 27 Jun 2018 08:08:31 +0000 (01:08 -0700)
Handle subnormal weights for choices()

Lib/random.py
Lib/test/test_random.py
Misc/NEWS.d/next/Library/2018-06-27-00-31-30.bpo-24567.FuePyY.rst [new file with mode: 0644]

index 1e0dcc87ed4a453ffdffef9a4ad32f8da766fd62..10069084916f66ea0a80e9680878364aae121c40 100644 (file)
@@ -383,7 +383,9 @@ class Random(_random.Random):
             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  -------------------
 
index e7ef68ba3d261507919010e3dd3e9d87086931e4..38fd8a9105ea1589fb240595d2b153e0625c4d68 100644 (file)
@@ -227,6 +227,14 @@ class TestBasicOps:
         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
diff --git a/Misc/NEWS.d/next/Library/2018-06-27-00-31-30.bpo-24567.FuePyY.rst b/Misc/NEWS.d/next/Library/2018-06-27-00-31-30.bpo-24567.FuePyY.rst
new file mode 100644 (file)
index 0000000..d496f2b
--- /dev/null
@@ -0,0 +1,2 @@
+Improve random.choices() to handle subnormal input weights that could
+occasionally trigger an IndexError.