Skip to content

Commit 0a18e05

Browse files
rhettingermiss-islington
authored andcommitted
Hoist the float conversion out of the inner loop. (pythonGH-10430)
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%).
1 parent cf5863f commit 0a18e05

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

Lib/random.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,14 +375,15 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
375375
if cum_weights is None:
376376
if weights is None:
377377
_int = int
378+
n += 0.0 # convert to float for a small speed improvement
378379
return [population[_int(random() * n)] for i in range(k)]
379380
cum_weights = list(_itertools.accumulate(weights))
380381
elif weights is not None:
381382
raise TypeError('Cannot specify both weights and cumulative weights')
382383
if len(cum_weights) != n:
383384
raise ValueError('The number of weights does not match the population')
384385
bisect = _bisect.bisect
385-
total = cum_weights[-1]
386+
total = cum_weights[-1] + 0.0 # convert to float
386387
hi = n - 1
387388
return [population[bisect(cum_weights, random() * total, 0, hi)]
388389
for i in range(k)]

0 commit comments

Comments
 (0)