Skip to content

Instantly share code, notes, and snippets.

@lemire
Created October 28, 2025 20:41
Show Gist options
  • Select an option

  • Save lemire/677fbe6cca870f2fc9ad5d5e8b06e2b5 to your computer and use it in GitHub Desktop.

Select an option

Save lemire/677fbe6cca870f2fc9ad5d5e8b06e2b5 to your computer and use it in GitHub Desktop.
random generation test
import random
def unbiased_random(s, L=32):
pow2 = 1 << L
if not (0 <= s <= pow2):
raise ValueError("s must be in [0, 2**L]")
if s == 0:
return 0
x = random.randrange(pow2)
m = x * s
l = m % pow2
if l < s: # line 4
t = (pow2 - s) % s
while l < t:
x = random.randrange(pow2)
m = x * s
l = m % pow2
return m // pow2
def test_uniformity(s=3, L=4, num_tests=5000000):
counts = {i: 0 for i in range(s)}
for _ in range(num_tests):
r = unbiased_random(s, L)
counts[r] += 1
print("Counts:")
for i in range(s):
print(f"{i}: {counts[i]} ({counts[i] / num_tests * 100:.2f}%)")
if __name__ == "__main__":
for i in range(1, 6):
test_uniformity()
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment