Python 中的随机数生成方法有何不同? [英] How do random number generation methods differ in Python?

查看:38
本文介绍了Python 中的随机数生成方法有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在 Python 中生成 0 到 10 之间的随机 int,我可以执行以下任一操作:

To generate a random int between 0 and 10 in Python, I could do any of the following:

import numpy as np
print(np.random.randint(0, 10))

import random
print(random.randint(0, 10))

这两种方法在计算上有何不同?

How do these two methods differ, computationally?

推荐答案

需要注意的是,这些函数并不等效.在numpy中,范围是[low, high),在Python中随机[low, high].

It's important to note that these function are not equivalent. In numpy, the range is [low, high), and in the Python random [low, high].

速度

看来numpy的实现是最快的:

It seems that the numpy implementation is the fastest:

In [1]: import numpy as np
In [2]: %timeit np.random.randint(0, 10)
1000000 loops, best of 3: 206 ns per loop

In [3]: import random
In [4]: %timeit random.randint(0, 10)    
1000000 loops, best of 3: 1.5 µs per loop

随机性

随机性似乎是一样的.可以使用 ent

The randomness seems to be the same. One can test the randomness using ent

对于这个脚本

import numpy as np
import sys

for _ in range(1000000):
    sys.stdout.write(str(np.random.randint(0, 10)))

命令的部分输出python file.py |ent -c

Value Char Occurrences Fraction  
 48   0       100360   0.100360  
 49   1       100157   0.100157  
 50   2        99958   0.099958  
 51   3       100359   0.100359  
 52   4       100287   0.100287  
 53   5       100022   0.100022  
 54   6        99909   0.099909  
 55   7        99143   0.099143  
 56   8       100119   0.100119  
 57   9        99686   0.099686  

Total:       1000000   1.000000  

Entropy = 3.321919 bits per byte.

对于这个脚本

import random
import sys

for _ in range(1000000):
    sys.stdout.write(str(random.randint(0, 9)))

命令的部分输出python file.py |ent -c

Value Char Occurrences Fraction  
 48   0       100372   0.100372  
 49   1       100491   0.100491  
 50   2        98988   0.098988  
 51   3       100557   0.100557  
 52   4       100227   0.100227  
 53   5       100004   0.100004  
 54   6        99520   0.099520  
 55   7       100148   0.100148  
 56   8        99736   0.099736  
 57   9        99957   0.099957  

Total:       1000000   1.000000  

Entropy = 3.321913 bits per byte.

这篇关于Python 中的随机数生成方法有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆