# 構造隨機數
~~~
import numpy as np
# 構造3行2列
# 值是從0到1的隨機數
print(np.random.rand(3, 2))
~~~
輸出
~~~
[[ 0.605721 0.3173085 ]
[ 0.7827691 0.01328121]
[ 0.28464864 0.41312727]]
~~~
# 構造指定范圍的隨機數
~~~
import numpy as np
# 隨機數是0-10,左閉右開,維度是5行4列
randint = np.random.randint(10, size=(5, 4))
print(randint)
~~~
返回
~~~
[[1 9 9 7]
[6 4 3 5]
[4 6 1 3]
[4 8 9 1]
[9 9 0 5]]
~~~
# 返回一個數
~~~
import numpy as np
sample = np.random.random_sample()
print(sample)
~~~
輸出
~~~
0.7799226901559352
~~~
隨機整數
~~~
import numpy as np
# 0-10之間,3個隨機整數,不包含10
randint = np.random.randint(0, 10, 3)
print(randint)
~~~
返回
~~~
0.7799226901559352
~~~
# 正態分布
~~~
import numpy as np
mu, sigma = 0, 0.1
# 我們要取10個數
normal = np.random.normal(mu, sigma, 10)
print(normal)
~~~
輸出
~~~
[-0.12014471 0.05975655 0.02498604 0.03608821 -0.03849737 0.0780996
-0.02089003 -0.02095987 -0.04824946 0.16148243]
~~~
# 設置顯示精度
~~~
import numpy as np
# 小數點后顯示3位
np.set_printoptions(precision=3)
mu, sigma = 0, 0.1
# 我們要取10個數
normal = np.random.normal(mu, sigma, 10)
print(normal)
~~~
輸出
~~~
[-0.112 -0.035 0.09 0.119 -0.03 -0.017 0.055 0.123 0.128 -0.151]
~~~
# 洗牌
~~~
import numpy as np
arange = np.arange(10)
print(arange)
# 進行洗牌
np.random.shuffle(arange)
print(arange)
~~~
輸出
~~~
[0 1 2 3 4 5 6 7 8 9]
[4 7 9 0 3 2 6 8 1 5]
~~~
# 指定種子
比如我們調試程序的時候,我們對比2個實驗,我們希望隨機數不變來對比下
~~~
import numpy as np
# 設置種子
np.random.seed(10)
mu, sigma = 0, 0.1
normal = np.random.normal(mu, sigma, 10)
print(normal)
~~~
無論輸出多少次,結果不變,在種子是一樣的情況下