Forked from gameguy43/testing distributions in rand5() functions
Last active
November 12, 2015 15:07
-
-
Save icholy/7dd45787868f1aaa4e52 to your computer and use it in GitHub Desktop.
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 | |
import math | |
def rand7(): | |
return random.randrange(1,8) | |
def rand5_mod(): | |
return rand7() % 5 + 1 | |
def rand5_recursive(): | |
roll = rand7() | |
return roll if roll <= 5 else rand5_recursive() | |
def rand5_while(): | |
result = 7 # arbitrarily large | |
while result > 5: | |
result = rand7() | |
return result | |
def rand5_scale(): | |
return int(math.ceil((rand7() / 7.0) * 5.0)) | |
def test_distributions(): | |
appearances = [0] * 10 | |
for time in range(1000000): | |
result = rand5_mod() | |
appearances[result] += 1 | |
print "rand5_mod" | |
print appearances | |
appearances = [0] * 10 | |
for time in range(1000000): | |
result = rand5_recursive() | |
appearances[result] += 1 | |
print "rand5_recursive" | |
print appearances | |
appearances = [0] * 10 | |
for time in range(1000000): | |
result = rand5_while() | |
appearances[result] += 1 | |
print "rand5_while" | |
print appearances | |
appearances = [0] * 10 | |
for time in range(1000000): | |
result = rand5_scale() | |
appearances[result] += 1 | |
print "rand5_scale" | |
print appearances |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment