kopia lustrzana https://github.com/micropython/micropython-lib
random: Add randrange() implementation.
The idea behind this implementation is that getrandbits() is guaranteed (required) to be equally distributed. Thus, we can just repeatedly sample it until get a suitable value, there's no bias accumulated and the process should be finite (and on average take few iterations).pull/226/merge
rodzic
693b229f8d
commit
ac6fcb4729
|
@ -0,0 +1,18 @@
|
|||
from urandom import *
|
||||
|
||||
|
||||
def randrange(start, stop=None):
|
||||
if stop is None:
|
||||
stop = start
|
||||
start = 0
|
||||
upper = stop - start
|
||||
bits = 0
|
||||
pwr2 = 1
|
||||
while upper > pwr2:
|
||||
pwr2 <<= 1
|
||||
bits += 1
|
||||
while True:
|
||||
r = getrandbits(bits)
|
||||
if r < upper:
|
||||
break
|
||||
return r + start
|
Ładowanie…
Reference in New Issue