Python如何生成指定區(qū)間中的隨機(jī)數(shù)
如何生成指定區(qū)間中的隨機(jī)數(shù)
要求生成區(qū)間[a, b]中的隨機(jī)數(shù)。若要求為浮點(diǎn)數(shù),則Python中只能近似達(dá)到這一要求,因?yàn)殡S機(jī)函數(shù)的取值區(qū)間一般都為左閉右開(kāi)區(qū)間,因?yàn)橹荒軣o(wú)限接近b。
若要求為整數(shù),那么將取數(shù)區(qū)間設(shè)置為[a,b+1)即可以取到b了。
具體如下:
1. random()
numpy.random.random(size=None)
- 生成[0.0, 1.0)的隨機(jī)數(shù)。注意區(qū)間是左閉右開(kāi),取不到1.0。
- 生成的是浮點(diǎn)數(shù)。
- 參數(shù)size可以用于指定生成隨機(jī)數(shù)的個(gè)數(shù)和形狀。例如
>>>import numpy as np >>>np.random.random() 0.5312959368718575 >>>np.random.random(5) array([ 0.2483017 , ?0.86182212, ?0.03454678, ?0.87525464, ?0.31962688]) >>>np.random.random((2,3)) array([[ 0.66214521, ?0.40083972, ?0.05552421], ? ? ? ?[ 0.51091912, ?0.6419505 , ?0.8757311 ]])
利用np.random.random()近似生成[a,b]的隨機(jī)數(shù),因?yàn)榍罢叩娜≈捣秶荹0,1),是半開(kāi)區(qū)間,所以右側(cè)端點(diǎn)處的值b取不到。
>>>import numpy as np >>>a + (b-a)*np.random.random()
2. rand()
numpy.random.rand(d0, d1, …, dn)
它和numpy.random.random(size=None)的主要區(qū)別就在于參數(shù)。例如生成2*3的array。注意觀察參數(shù)的形式。
>>>import numpy as np >>>np.random.random((2,3)) array([[ 0.66214521, ?0.40083972, ?0.05552421], ? ? ? ?[ 0.51091912, ?0.6419505 , ?0.8757311 ]]) >>>np.random.rand(2,3) array([[ 0.59786635, ?0.88902485, ?0.7038246 ], ? ? ? ?[ 0.44150109, ?0.73660019, ?0.70001489]])
3. randint()
生成指定區(qū)間的隨機(jī)整數(shù)
numpy.random.randint(low, high=None, size=None, dtype=‘l') >>> np.random.randint(2,5) 3 >>> np.random.randint(2,5,3) array([2, 3, 3]) >>> np.random.randint(2,5,9) array([3, 4, 3, 2, 3, 3, 4, 4, 2]) >>> np.random.randint(2,5,(2,3)) array([[4, 3, 2], ? ? ? ?[3, 3, 4]])
注意:取值的區(qū)間仍然是左閉右開(kāi)區(qū)間[low, high)
若要求取[a,b]中的隨機(jī)數(shù),則
>>>np.random.randint(a, b+1)
python生成隨機(jī)數(shù)總結(jié)
生成隨機(jī)數(shù)和隨機(jī)數(shù)操作
Python有自己專門處理隨機(jī)數(shù)的功能,但大家最常用的還是numpy庫(kù)里的生成隨機(jī)數(shù)功能,因?yàn)镻ython 的 random 沒(méi)有考慮數(shù)組類型的高效數(shù)據(jù)結(jié)構(gòu),所以在 array 類型的數(shù)據(jù)結(jié)構(gòu)時(shí),大家更喜歡直接用 Numpy 來(lái)生成,且它的功能更豐富,有各種隨機(jī)數(shù)的生成方式,隨機(jī)化當(dāng)前數(shù)列,加速等。
Python自帶random
import random print(random.random()) # 隨機(jī)生成一個(gè)0-1之間的隨機(jī)數(shù),例如0.7679099295136553 print(random.randint(1, 10)) # 隨機(jī)生成一個(gè)1-10之間的整數(shù),如3
numpy庫(kù)的random
先導(dǎo)入庫(kù)
import numpy as np
1. np.random.random_integers
numpy.random.random_integers(low, high=None, size=None)
- 返回隨機(jī)整數(shù),范圍區(qū)間為[low,high],包含low和high
- 參數(shù):low為最小值,high為最大值,size為數(shù)組維度大小
- high沒(méi)有填寫時(shí),默認(rèn)生成隨機(jī)數(shù)的范圍是[1,low]
該函數(shù)在最新的numpy版本中已被替代,建議使用randint函數(shù)
>>> np.random.random_integers(1,size=5) array([1, 1, 1, 1, 1])
2. np.random.rand() 或 np.random.random()
# 功能一樣,寫法有點(diǎn)區(qū)別 np.random.rand(d0,d1,…,dn) np.random.random([d0,d1,…,dn])
- rand函數(shù)根據(jù)給定維度,生成[0,1)之間的數(shù)據(jù),包含0,不包含1
- dn:生成維度
- 返回值為指定維度的array
>>> np.random.rand(4,2) array([[ 0.02173903, ?0.44376568], ? ? ? ?[ 0.25309942, ?0.85259262], ? ? ? ?[ 0.56465709, ?0.95135013], ? ? ? ?[ 0.14145746, ?0.55389458]]) >>> np.random.rand(4,3,2) # shape: 4*3*2 array([[[ 0.08256277, ?0.11408276], ? ? ? ? [ 0.11182496, ?0.51452019], ? ? ? ? [ 0.09731856, ?0.18279204]], ? ? ? ? ?[[ 0.74637005, ?0.76065562], ? ? ? ? [ 0.32060311, ?0.69410458], ? ? ? ? [ 0.28890543, ?0.68532579]], ? ? ? ? ?[[ 0.72110169, ?0.52517524], ? ? ? ? [ 0.32876607, ?0.66632414], ? ? ? ? [ 0.45762399, ?0.49176764]], ? ? ? ? ?[[ 0.73886671, ?0.81877121], ? ? ? ? [ 0.03984658, ?0.99454548], ? ? ? ? [ 0.18205926, ?0.99637823]]])
3. np.random.randn()
numpy.random.randn(d0,d1,…,dn)
- randn函數(shù)返回一個(gè)或一組樣本,具有標(biāo)準(zhǔn)正態(tài)分布(u分布,0為均值、1為標(biāo)準(zhǔn)差的正態(tài)分布,記為N(0,1))。
- dn:維度
- 返回值為指定維度的array
>>> np.random.randn() # 當(dāng)沒(méi)有參數(shù)時(shí),返回單個(gè)數(shù)據(jù) -1.1241580894939212 >>> np.random.randn(2,4) array([[ 0.27795239, -2.57882503, ?0.3817649 , ?1.42367345], ? ? ? ?[-1.16724625, -0.22408299, ?0.63006614, -0.41714538]]) ? ? ? ? >>> np.random.randn(4,3,2) array([[[ 1.27820764, ?0.92479163], ? ? ? ? [-0.15151257, ?1.3428253 ], ? ? ? ? [-1.30948998, ?0.15493686]], ? ? ? ? ?[[-1.49645411, -0.27724089], ? ? ? ? [ 0.71590275, ?0.81377671], ? ? ? ? [-0.71833341, ?1.61637676]], ? ? ? ? ?[[ 0.52486563, -1.7345101 ], ? ? ? ? [ 1.24456943, -0.10902915], ? ? ? ? [ 1.27292735, -0.00926068]], ? ? ? ? ?[[ 0.88303 ? , ?0.46116413], ? ? ? ? [ 0.13305507, ?2.44968809], ? ? ? ? [-0.73132153, -0.88586716]]])
上面生成的都是小數(shù),下面生成整數(shù)
4. np.random.randint()
numpy.random.randint(low, high=None, size=None, dtype='l')
函數(shù)作用:返回一個(gè)隨機(jī)整型數(shù)或隨機(jī)數(shù)數(shù)組,范圍從低(閉)到高(開(kāi)),即[low, high)。
如果沒(méi)有寫參數(shù)high的值,則返回[0,low)的值。
參數(shù)如下:
low
: int生成的數(shù)值最低要大于等于low。(hign = None時(shí),生成的數(shù)值要在[0, low)區(qū)間內(nèi))high
: int (可選)如果使用這個(gè)值,則生成的數(shù)值在[low, high)區(qū)間。size
: int or tuple of ints(可選)輸出隨機(jī)數(shù)的尺寸,比如size = (m * n* k)則輸出同規(guī)模即m * n* k個(gè)隨機(jī)數(shù)。默認(rèn)是None的,僅僅返回滿足要求的單一隨機(jī)數(shù)。dtype
: dtype(可選):想要輸出的格式。如int64、int等等
注:范圍不對(duì)有可能報(bào)錯(cuò) ValueError: low >= high
>>> np.random.randint(2, size=10) array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) >>>np.random.randint(2, high=10, size=(2,3)) array([[6, 8, 7], ? ? ? ?[2, 5, 2]])
5. np.random.choice()
numpy.random.choice(a, size=None, replace=True, p=None)
- 從給定的一維數(shù)組中生成隨機(jī)數(shù)
- 參數(shù): a為一維數(shù)組類似數(shù)據(jù)或整數(shù);size為數(shù)組維度;p為數(shù)組中的數(shù)據(jù)出現(xiàn)的概率|權(quán)重
- a為整數(shù)時(shí),對(duì)應(yīng)的一維數(shù)組為np.arange(a)
>>> np.random.choice(5,3) array([4, 1, 4]) >>> np.random.choice(5, 3, replace=False) # 當(dāng)replace為False時(shí),生成的隨機(jī)數(shù)不能有重復(fù)的數(shù)值(放不放回) array([0, 3, 1]) >>> np.random.choice(5,size=(3,2)) array([[1, 0], ? ? ? ?[4, 2], ? ? ? ?[3, 3]]) ? ? ? ? >>> demo_list = ['lenovo', 'sansumg','moto','xiaomi', 'iphone'] >>> np.random.choice(demo_list,size=(3,3)) array([['moto', 'iphone', 'xiaomi'], ? ? ? ?['lenovo', 'xiaomi', 'xiaomi'], ? ? ? ?['xiaomi', 'lenovo', 'iphone']], ? ? ? dtype='<U7')
- 參數(shù)p的長(zhǎng)度與參數(shù)a的長(zhǎng)度需要一致;
- 參數(shù)p為概率,p里的數(shù)據(jù)之和應(yīng)為1.
>>> demo_list = ['lenovo', 'sansumg','moto','xiaomi', 'iphone'] >>> np.random.choice(demo_list,size=(3,3), p=[0.1,0.6,0.1,0.1,0.1]) array([['sansumg', 'sansumg', 'sansumg'], ? ? ? ?['sansumg', 'sansumg', 'sansumg'], ? ? ? ?['sansumg', 'xiaomi', 'iphone']], ? ? ? dtype='<U7')
6. np.random.seed()
- np.random.seed()的作用:使得隨機(jī)數(shù)據(jù)可預(yù)測(cè)。
- 當(dāng)我們?cè)O(shè)置相同的seed,每次生成的隨機(jī)數(shù)相同。如果不設(shè)置seed,則每次會(huì)生成不同的隨機(jī)數(shù)
- 當(dāng)我們把種子seed固定的時(shí)候(用一個(gè)數(shù)字),同一個(gè)種子(數(shù)字)產(chǎn)生的隨機(jī)序列就會(huì)一樣。
>>> np.random.seed(0) >>> np.random.rand(5) array([ 0.5488135 , ?0.71518937, ?0.60276338, ?0.54488318, ?0.4236548 ]) >>> np.random.seed(1676) >>> np.random.rand(5) array([ 0.39983389, ?0.29426895, ?0.89541728, ?0.71807369, ?0.3531823 ]) >>> np.random.seed(1676) >>> np.random.rand(5) array([ 0.39983389, ?0.29426895, ?0.89541728, ?0.71807369, ?0.3531823 ]) ? ?
7. 隨機(jī)分布
我們?cè)谏蓴?shù)據(jù)的時(shí)候,有時(shí)需要按照特定的統(tǒng)計(jì)學(xué)分布來(lái)生成,比如一個(gè)正態(tài)分布的抽樣數(shù)據(jù),或者均勻分布的數(shù)據(jù)抽樣結(jié)果,又或者泊松分布等等,都可以用 Numpy 來(lái)實(shí)現(xiàn)。機(jī)器學(xué)習(xí)中比較常用的 正態(tài)分布 和 均勻分布。
# (均值,方差,size) print("正態(tài)分布:", np.random.normal(1, 0.2, 10)) # (最低,最高,size) print("均勻分布:", np.random.uniform(-1, 1, 10))
8. 打亂功能
np.random.permutation(), 它實(shí)現(xiàn)的是 np.random.shuffle() 的一種特殊形式。
可以說(shuō)是一種簡(jiǎn)單處理特殊情況的功能。
它有兩個(gè)方便之處:
- 1. 直接生成亂序的序列號(hào)
- 2. 對(duì)數(shù)據(jù)亂序
相比 np.random.shuffle(),permutation 有一個(gè)好處,就是可以返回一個(gè)新數(shù)據(jù),對(duì)原本的數(shù)據(jù)沒(méi)有影響。而且還可以處理多維數(shù)據(jù)。
np.random.permutation(10)) # 直接出10個(gè)亂序數(shù) data = np.arange(12).reshape([6,2]) np.random.permutation(data)) # 將數(shù)據(jù)在第一維度上打亂
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python之tensorflow手把手實(shí)例講解斑馬線識(shí)別實(shí)現(xiàn)
目前智慧城市的發(fā)展,人們生活處處有科技,比如人臉識(shí)別,智慧交通,無(wú)人駕駛等前沿的科技產(chǎn)品也都融入了人們生活中;本篇文章帶你從頭開(kāi)始實(shí)現(xiàn)斑馬線識(shí)別2021-09-09Python Pandas常用函數(shù)方法總結(jié)
今天給大家?guī)?lái)的是關(guān)于Python的相關(guān)知識(shí),文章圍繞著Pandas常用函數(shù)方法展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06python?playwright?庫(kù)上傳和下載操作(自動(dòng)化測(cè)試?playwright)
這篇文章主要介紹了python?playwright?庫(kù)上傳和下載操作(自動(dòng)化測(cè)試?playwright?),playwright中的上傳和下載比selenium的上傳和下載要簡(jiǎn)便些,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05python實(shí)戰(zhàn)之德州撲克第二步-判斷牌型
這篇文章主要介紹了python實(shí)戰(zhàn)之德州撲克第二步-判斷牌型,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04獲取django框架orm query執(zhí)行的sql語(yǔ)句實(shí)現(xiàn)方法分析
這篇文章主要介紹了獲取django框架orm query執(zhí)行的sql語(yǔ)句實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Django框架中orm query執(zhí)行的sql語(yǔ)句獲取方法相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-06-06Python 序列化 pickle/cPickle模塊使用介紹
這篇文章主要介紹了Python 序列化 pickle/cPickle模塊使用介紹,需要的朋友可以參考下2014-11-11Python AutoCAD 系統(tǒng)設(shè)置的實(shí)現(xiàn)方法
這篇文章主要介紹了Python AutoCAD 系統(tǒng)設(shè)置的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04淺談python下含中文字符串正則表達(dá)式的編碼問(wèn)題
今天小編就為大家分享一篇淺談python下含中文字符串正則表達(dá)式的編碼問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12