Skip to content

Instantly share code, notes, and snippets.

@icholy
Forked from gameguy43/testing distributions in rand5() functions
Last active November 12, 2015 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icholy/7dd45787868f1aaa4e52 to your computer and use it in GitHub Desktop.
Save icholy/7dd45787868f1aaa4e52 to your computer and use it in GitHub Desktop.
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