Created
August 13, 2019 17:52
-
-
Save jgrahamc/eec0d6fc6c5f2f97592e411be8bc6833 to your computer and use it in GitHub Desktop.
Implementation of Knuth's bad random number generator from TAOCP Volume 2, Chapter 3
This file contains 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
ten5 = 100000 | |
ten8 = 100000000 | |
ten9 = 1000000000 | |
ten10 = 10000000000 | |
def krng(x): | |
iterations = x/ten9 + 1 | |
while iterations > 0: | |
step = (x/ten8) % 10 + 3 | |
if step == 3: | |
if x < 5000000000L: | |
x += 5000000000L | |
step += 1 | |
if step == 4: | |
x = ((x*x)/ten5) % ten10 | |
step += 1 | |
if step == 5: | |
x = (1001001001L*x) % ten10 | |
step += 1 | |
if step == 6: | |
if x < ten8: | |
x += 9814055677L | |
else: | |
x = ten10 - x | |
step += 1 | |
if step == 7: | |
x = ten5*(x % ten5) + (x/ten5) | |
step += 1 | |
if step == 8: | |
x = (1001001001L*x) % ten10 | |
step += 1 | |
if step == 9: | |
s = 1 | |
t = x | |
for i in range(10): | |
if t % 10 > 0: | |
x -= s | |
s *= 10 | |
t /= 10 | |
step += 1 | |
if step == 10: | |
if x < ten5: | |
x = x*x + 99999L | |
else: | |
x -= 99999L | |
step += 1 | |
if step == 11: | |
while x < ten9: | |
x *= 10 | |
step += 1 | |
if step == 12: | |
x = ((x*(x-1))/ten5) % ten10 | |
step += 1 | |
iterations -= 1 | |
return int(x) | |
print krng(6065038420L) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment