]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Hoist the float conversion out of the inner loop. (GH-10430)
authorRaymond Hettinger <rhettinger@users.noreply.github.com>
Fri, 9 Nov 2018 10:39:50 +0000 (02:39 -0800)
committerMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Fri, 9 Nov 2018 10:39:50 +0000 (02:39 -0800)
Currently, the *n* and *total* variables get converted to floats each time they are multiplied by random().  This minor tweak does the conversion just once and gets a small speedup (approx 3%).

Lib/random.py

index b2c0d6fcc3b832258e47ec0bb5685d6ab341c4c7..4b51b6696bfcd41f914e087bd39d2f3e07ea6a78 100644 (file)
@@ -375,6 +375,7 @@ class Random(_random.Random):
         if cum_weights is None:
             if weights is None:
                 _int = int
+                n += 0.0    # convert to float for a small speed improvement
                 return [population[_int(random() * n)] for i in range(k)]
             cum_weights = list(_itertools.accumulate(weights))
         elif weights is not None:
@@ -382,7 +383,7 @@ class Random(_random.Random):
         if len(cum_weights) != n:
             raise ValueError('The number of weights does not match the population')
         bisect = _bisect.bisect
-        total = cum_weights[-1]
+        total = cum_weights[-1] + 0.0   # convert to float
         hi = n - 1
         return [population[bisect(cum_weights, random() * total, 0, hi)]
                 for i in range(k)]