Python中的骰子滚子不是随机的

时间:2018-07-22 15:10:24

标签: python

我最近用python制作了一个骰子滚轴。但是,输出似乎是相当随机的(例如,数字连续两次连续出现)。这是因为我的代码不好,还是random.randint函数看起来不那么随机?

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()

2 个答案:

答案 0 :(得分:3)

验证函数随机性的一种方法是调用它足够的次数,并验证输出分布。下面的代码这样做。

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)))

这产生了:

Pr(1) = 0.16546
Pr(2) = 0.16777
Pr(3) = 0.16613
Pr(4) = 0.16534
Pr(5) = 0.1675
Pr(6) = 0.1678

这似乎是完全随机的。

答案 1 :(得分:0)

正如@Arne在评论中所指出的那样,在“随机”卷中重复进行骰子滚动是理想的行为(在这种情况下,是伪随机,但我敢肯定它不会对您的应用程序有所影响)。 / p>

但是,如果重复确实困扰着您,那么防止重新滚动就很困难了,例如以下:

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