I was researching how floats are stored in a computer and was trying to think up a way to generate random values between 0 and 1. Python already provides an implementation allowing this already, and two of the functions below are directly inspired by that code, but the third is a slightly different way of doing the same thing. A similar version of this code has been used to implement similar functionality in C# at one time. Others might also find it useful if they want to create equivalent code in a separate language while having access to random bytes but not random floats. It should be noted that the various implementations get slower as you go down the list.
1 2 3 4 5 6 7 8 9 10 11 12 13
import os import struct def random_1(): return (int.from_bytes(os.urandom(7), 'big') >> 3) * 2 ** -53 def random_2(): return (int.from_bytes(os.urandom(7), 'big') >> 3) / (1 << 53) def random_3(): array = bytearray(b'\x3F' + os.urandom(7)) array |= 0xF0 return struct.unpack('>d', array) - 1
If anyone can think up other ways to generate floats between 0 and 1, they would be nice to see. Someone might have a particularly ingenious way of doing this that others have not seen yet.