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

Python中的骰子滚轮不是随机的,python,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('

我最近用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()

正如@Arne在评论中所注意到的,骰子掷骰重复是“随机”掷骰中所需要的行为(在本例中,是伪随机的,但我很确定这对您的应用程序没有影响)

但是,如果重复确实困扰您,则不难防止重新滚动,例如以下情况:

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

正如@Arne在评论中所注意到的,骰子掷骰重复是“随机”掷骰中所需要的行为(在本例中,是伪随机的,但我很确定这对您的应用程序没有影响)

但是,如果重复确实困扰您,则不难防止重新滚动,例如以下情况:

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

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

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

这似乎是完全随机的

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

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

这似乎是完全随机的

一个数字不能连续出现两次的掷骰机是有偏差的,而不是随机的。你的代码看起来没有问题。这是一个完全正常的代码。在现实生活中,同一个数字有可能出现两次。随机性不能保证任何特定的顺序,它只提供均匀分布,这意味着当样本数接近无穷大时,所有6个数字都会出现相同的次数。事实上,你已经陷入了为什么对我的答案进行向下投票的问题中:3A掷骰子时,如果数字不能连续出现两次,那将是有偏的,而不是随机的。你的代码看起来没有问题。这是一个完全正常的代码。在现实生活中,同一个数字有可能出现两次。随机性不能保证任何特定的顺序,它只提供均匀分布,这意味着当样本数接近无穷大时,所有6个数字都会出现相同的次数。实际上,你已经陷入了为什么对我的答案投反对票的问题:3在第一次迭代中
垃圾邮件
没有定义。此外,还有更简单的方法来确保不生成2个数字。在第一次迭代中,未定义
spam
。此外,还有更简单的方法来确保不生成2个数字。