Reputation: 23
I made a dice roller in python recently. However, the outputs seem to be fairly non-random (e.g. numbers coming up regularly twice in a row). Is this to do with my poor code or is the random.randint function not as random as it seems?
import random
print('Welcome to Dice Rolling simulator! \
Type "Roll" to start.')
def DiceRoll():
if input() == (str('Roll')):
print(spam)
print('Roll again?')
for i in range (50):
spam = random.randint(1,6)
DiceRoll()
Upvotes: 0
Views: 1127
Reputation: 105
One way to verify the randomness of your function is to call it enough times, and verify the output distribution. The following code does so.
import random
def DiceRoll():
return random.randint(1,6)
hist = []
for i in range(100000):
hist.append(DiceRoll())
for j in range(1,7):
print("Pr({}) = {}".format(j,hist.count(j)/len(hist)))
This yields :
Pr(1) = 0.16546
Pr(2) = 0.16777
Pr(3) = 0.16613
Pr(4) = 0.16534
Pr(5) = 0.1675
Pr(6) = 0.1678
Which seems to be perfectly random.
Upvotes: 3
Reputation: 1559
As @Arne noticed in the comments, dice rolls repeating is desired behavior in "random" rolls (in this case, pseudo-random, but I'm pretty sure it doesn't make a difference for your application).
However, if the repeats are really bothering you, it wouldn't be hard to prevent re-rolls, e.g. the following:
import random
print('Welcome to Dice Rolling simulator! \
Type "Roll" to start.')
spam = random.randint(1,6)
def DiceRoll(spam):
if input() == (str('Roll')):
print(spam)
print('Roll again?')
for i in range (50):
DiceRoll(spam)
spam2 = random.randint(1,5)
spam = spam2//spam*(spam+1) + spam2%spam
Upvotes: 0