Skip to content

Instantly share code, notes, and snippets.

@NassimBentarka
Created July 25, 2021 20:11
Show Gist options
  • Save NassimBentarka/5c812cb24182d2600bf086b29245e61d to your computer and use it in GitHub Desktop.
Save NassimBentarka/5c812cb24182d2600bf086b29245e61d to your computer and use it in GitHub Desktop.
Random number generator that uses /dev/random as entropy source. Written as part of an experiment on the potential influences of the mind on the randomness of an event: a coin toss in this case.
#!/usr/bin/env python3
import random
import matplotlib as plt
import time
import os
import struct
_random_source = open("/dev/random", "rb")
def random_bytes(len):
return _random_source.read(len)
def unpack_uint32(bytes):
tup = struct.unpack("I", bytes)
return tup[0]
UINT32_MAX = 0xffffffff
def randint(low, high):
"""
Return a random integer in the range [low, high], including
both endpoints.
"""
n = (high - low) + 1
assert n >= 1
scale_factor = n / float(UINT32_MAX + 1)
random_uint32 = unpack_uint32(random_bytes(4))
result = int(scale_factor * random_uint32) + low
return result
def randint_gen(low, high, count):
"""
Generator that yields random integers in the range [low, high],
including both endpoints.
"""
n = (high - low) + 1
assert n >= 1
scale_factor = n / float(UINT32_MAX + 1)
for _ in range(count):
random_uint32 = unpack_uint32(random_bytes(4))
result = int(scale_factor * random_uint32) + low
yield result
def stopwatch(seconds):
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
print("loop cycle time: %f, seconds count: %02d" % (time.clock() , elapsed))
time.sleep(1)
if __name__ == "__main__":
# roll 2 dice individually with randint()
result = [randint(0, 1) for _ in range(2)]
print(result)
# roll 2 dice more efficiently with randint_gen()
print(list(randint_gen(0, 1, 2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment