新聞中心
python生產(chǎn)隨機數(shù)字的方法是:1、利用random庫的randint函數(shù)生成隨機整數(shù)、uniform函數(shù)隨機生成浮點數(shù)等;2、利用第三方庫numpy中randn函數(shù)生成符合正態(tài)分布的隨機矩陣。
在Python中可以用于隨機數(shù)生成的有兩種主要途徑,一是random模塊,另一個是numpy庫中random函數(shù)。
OUTLINE
-
random模塊
-
numpy中的random函數(shù)
-
總結(jié)
random模塊
random模塊中將近有7個函數(shù)都是可以用來生成隨機數(shù)的:
① random.random()
功能:隨機生成一個 [0,1) 的浮點數(shù)
用法:
import random number = random.random() # 輸出:0.7178886135325596
② random.uniform(a,b)
功能:隨機生成一個 [a,b) 的浮點數(shù)
用法:
number = random.uniform(2,4) # 輸出:2.070517705689751
③ random.randint(a,b)
功能:隨機生成一個 [a,b] 的整數(shù)
用法:
number = random.randint(2,4) # 輸出:3
④ random.randrange(a,b,step)
功能:在生成的<以a為始,每step遞增,以b為終>這樣的一個整數(shù)序列中隨機選擇一個數(shù)
用法:
number = random.randrange(2,10,2) # 輸出:2
⑤ random.choice(sequence)
功能:從一個已有的sequence中隨機選擇一個元素
用法:
number = random.choice(range(2,10))
# 輸出:6
number = random.choice('anbegvdje')
# 輸出:g⑥ random.sample(sequence,k)
功能:從某一序列中獲取指定長度的片段
用法:
a = ['香蕉','蘋果','橘子','眼影','眼線'] b = random.sample(a,2)# 輸出:['橘子', '蘋果']
⑦ random.shuffle(列表)
功能:打亂一個列表的元素順序
用法:
a = ['香蕉','蘋果','橘子','眼影','眼線'] random.shuffle(a) # 打亂這個操作不需要重新定義對象,它作用的是對象本身 # 輸出:['眼線', '蘋果', '眼影', '橘子', '香蕉']
numpy中的random函數(shù)
numpy中的random函數(shù)可以調(diào)用的方法主要有兩種,一種是生成隨機浮點數(shù),二是生成隨機整數(shù)。
① np.random.randn(a,b)
功能:生成a*b維的隨機數(shù),且該數(shù)服從標(biāo)準(zhǔn)正太分布
用法:
data = np.random.randn(5,4) # 輸出: array([[-1.6101468 , -0.81103612, 0.44875047, 0.55987574], [-0.33322916, 0.18676658, -0.18424432, -0.84435811], [ 0.57654276, 0.28830858, -0.73403656, 1.59404864], [ 0.39009202, 0.86239796, 0.66290243, -0.61292579], [ 0.03081516, 0.99335315, -0.6875357 , 0.90552971]])
② random.randint(low,high,size)
功能:生成一個<以low為下限,high為上限,size大小>的隨機整數(shù)矩陣,其中數(shù)值范圍包含low,不包含high
用法:
data = np.random.randint(low=2,high=5,size=(5,7)) # 輸出: array([[4, 2, 4, 4, 4, 4, 2], [4, 2, 2, 4, 3, 3, 3], [3, 4, 3, 4, 3, 3, 4], [3, 4, 2, 3, 3, 2, 2], [3, 3, 3, 3, 2, 3, 2]])
總結(jié)
1、在我們?nèi)粘J褂弥?,如果是為了得到隨機的單個數(shù),多考慮random模塊;如果是為了得到隨機小數(shù)或者整數(shù)的矩陣,就多考慮numpy中的random函數(shù);
2、對于random模塊的函數(shù)調(diào)用方法的記憶,可以多從它本身的英譯出發(fā),并多比較其不同從而加深理解~
推薦課程:Introduction to Even More Python for Beginners(微軟官方課程)
本文名稱:創(chuàng)新互聯(lián)Python教程:python如何生產(chǎn)隨機數(shù)字
分享URL:http://fisionsoft.com.cn/article/coipgid.html


咨詢
建站咨詢

