diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2018-11-09 10:39:50 (GMT) |
---|---|---|
committer | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2018-11-09 10:39:50 (GMT) |
commit | 0a18e0510a145427d8ff1864a011c81ea02cdcd4 (patch) | |
tree | 1f9e4f52be6672e8fc802e0276c4638db1eaf28c /Lib/random.py | |
parent | cf5863faabe011a61827b9b9982dba3d6a381f0f (diff) | |
download | cpython-0a18e0510a145427d8ff1864a011c81ea02cdcd4.zip cpython-0a18e0510a145427d8ff1864a011c81ea02cdcd4.tar.gz cpython-0a18e0510a145427d8ff1864a011c81ea02cdcd4.tar.bz2 |
Hoist the float conversion out of the inner loop. (GH-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%).
Diffstat (limited to 'Lib/random.py')
-rw-r--r-- | Lib/random.py | 3 |
1 files changed, 2 insertions, 1 deletions
diff --git a/Lib/random.py b/Lib/random.py index b2c0d6f..4b51b66 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -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)] |