Created
October 28, 2025 20:41
-
-
Save lemire/677fbe6cca870f2fc9ad5d5e8b06e2b5 to your computer and use it in GitHub Desktop.
random generation test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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