Python中的随机数生成方法有何不同?
要在Python中生成介于0和10之间的随机Python中的随机数生成方法有何不同?,python,methods,Python,Methods,要在Python中生成介于0和10之间的随机int,我可以执行以下任一操作: import numpy as np print(np.random.randint(0, 10)) 或 这两种方法在计算上有什么不同?需要注意的是,这两种函数并不等价。在numpy中,范围是[low,high),在Python random中范围是[low,high] 速度 numpy的实现似乎是最快的: [1]中的:将numpy作为np导入 在[2]中:%timeit np.random.randint(0,10
int
,我可以执行以下任一操作:
import numpy as np
print(np.random.randint(0, 10))
或
这两种方法在计算上有什么不同?需要注意的是,这两种函数并不等价。在numpy中,范围是
[low,high)
,在Python random中范围是[low,high]
速度
numpy的实现似乎是最快的:
[1]中的:将numpy作为np导入
在[2]中:%timeit np.random.randint(0,10)
1000000个循环,最好3个:每个循环206纳秒
在[3]中:导入随机
在[4]中:%timeit random.randint(0,10)
1000000个回路,最好为3个:每个回路1.5µs
随机性
随机性似乎是一样的。我们可以使用
对于这个脚本
import numpy as np
import sys
for _ in range(1000000):
sys.stdout.write(str(np.random.randint(0, 10)))
import random
import sys
for _ in range(1000000):
sys.stdout.write(str(random.randint(0, 9)))
命令python file.py | ent-c
的部分输出为
值
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
总数:10000011000000
熵=每字节3.321919位。
这个剧本呢
import numpy as np
import sys
for _ in range(1000000):
sys.stdout.write(str(np.random.randint(0, 10)))
import random
import sys
for _ in range(1000000):
sys.stdout.write(str(random.randint(0, 9)))
命令python file.py | ent-c
的部分输出为
值
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
总数:10000011000000
熵=3.321913位/字节。
可能更重要的是哪一个更“随机”。似乎两者都是同样随机的。