3
在Python生成隨機int
介於0和10,我可以做任何以下的:Python中的隨機數生成方法如何不同?
import numpy as np
print(np.random.randint(0, 10))
或
import random
print(random.randint(0, 10))
如何這兩種方法的不同,計算?
在Python生成隨機int
介於0和10,我可以做任何以下的:Python中的隨機數生成方法如何不同?
import numpy as np
print(np.random.randint(0, 10))
或
import random
print(random.randint(0, 10))
如何這兩種方法的不同,計算?
重要的是要注意這些功能是不相同的。在numpy中,範圍是[low, high)
,並且在Python中隨機[low, high]
。
速度
看來,numpy的實現是最快的:
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
隨機性對於此腳本
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.
可能更重要的是哪一個更「隨機」。 – Barmar
看來,這兩者同樣是隨機的。 – malbarbo