Python随机不起作用

Pre*_*eom 5 python random numpy

尝试的问题:两个骰子中的一个骰子的价值高于第三个骰子的概率.

问题:出于某种原因,当我使用randompython中的模块(特别是示例方法)时,我最终会得到与使用numpy时不同(且不正确)的结果.我把结果包括在底部.重复执行代码会产生类似的结果.任何想法,为什么random.sample方法和numpy.random.random_integers有不同的结果,即使它们具有相同的功能?

import numpy as np                                                              
import random                                                                   


random_list = []                                                                
numpy_list = []                                                                 
n= 500                                                                          
np_wins = 0                                                                     
rand_wins = 0                                                                   
for i in range(n):                                                              
    rolls = random.sample(range(1,7), 3)                                        
    rand_wins += any(rolls[0] < roll for roll in rolls)                         

    rolls = np.random.random_integers(1, 6, 3)                                  
    np_wins += any(rolls[0] < roll for roll in rolls)                           


print "numpy : {}".format(np_wins/(n * 1.0))                                    
print "random : {}".format(rand_wins/(n * 1.0))           
Run Code Online (Sandbox Code Playgroud)

结果:


Press ENTER or type command to continue
numpy : 0.586
random : 0.688

rro*_*ndd 5

观察到差异的原因是random.sample没有替换的样本(参见此处),而numpy.random.random_integers有替换的样本。