I'm trying to simulate dnd dice rolls to get evenly distributed numbers between 1 and (for this example) 14.
The code I have is as follows:
from random import randint
def r(n):
return randint(1, n)
def d4():
return r(4)
def d8():
return r(8)
def d2():
return d4()%2+1
def d7():
res = d8()
while res == 8:
res = d8()
return res
def d14():
return d7()*d2()
# sim
from collections import Counter
res = Counter()
for i in range(100000):
res[d14()] += 1
t = 0
for k in sorted(res.keys()):
print(k, res[k])
t += res[k]
print(t)
I checked the d2 and d7 separately, and they seem to function correctly.
The sim part is just to check that every result is equally likely, but the output seems off.
1 7185
2 14260
3 7220
4 14276
5 7239
6 14349
7 7171
8 6992
10 7078
12 7124
14 7106
100000
This is what it outputed this time. It seems that 2, 4 and 6 are twice as likely to come up as anything else. Sometimes it changes without me changing the code, but that is expected as it should be random, but there are always numbers that are twice as likely to come up, and they are always even. I've done the math, and hopefully correctly, and it obviously shouldn't happen.
Is my code wrong or is there something about the randint function itself I don't know?