1. 程式人生 > >Python隨機數、隨機序列生成

Python隨機數、隨機序列生成

主要包括兩部分,第一部分是對官方文件的簡要總結,第二部分是一些實際應用中使用到的隨機數he隨機陣列生成例子, 第三部分是Numpy隨機數生成。

1. 偽隨機數生成模組

Python有一個偽隨機數生成模組 random.py 官方文件
用於生成各種偽隨機數。

(1) 生成一個數

random.randrange(stop)
random.randrange(start, stop[, step])
從給定的範圍隨機選擇一個整數返回。
random.randint(a, b)
返回一個隨機整數N,a<=N<=b,等價於random.randrange(a, b+1)


>>> randrange(10)                        # Integer from 0 to 9 inclusive
7
>>> randrange(0, 101, 2)                 # Even integer from 0 to 100 inclusive
26

(2)在序列中的應用

random.choice(seq)
從非空的序列中隨機選擇一個整數返回,如果序列為空,IndexError。


>>> choice(['win', 'lose', 'draw'])
# Single random element from a sequence 'draw'

random.choices(population, weights=None, *, cum_weights=None, k=1)
Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError. (隨機返回一個population的子集,大小為k)
random.shuffle(x[, random])


Shuffle the sequence x in place.(隨機打亂序列x的順序)
這裡的打亂是原地打亂


>>> deck = 'ace two three four'.split()
>>> shuffle(deck)                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence or set.(從序列population中隨機返回沒有重複的子集,大小為k)
這裡的操作不會改變原來的序列,返回的是一個新的序列。


>>> sample([10, 20, 30, 40, 50], k=4)    # Four samples without replacement
[40, 10, 50, 30]

(3)實數值分佈應用
random.random()
Return the next random floating point number in the range [0.0, 1.0).(隨機返回一個0.0-1.0的浮點數)


>>> random()                             # Random float:  0.0 <= x < 1.0
0.37444887175646646

random.uniform(a, b)
Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.
隨機返回一個屬於[a, b]或者[b, a]浮點數。


>>> uniform(2.5, 10.0)                   # Random float:  2.5 <= x < 10.0
3.1800146073117523

random.triangular(low, high, mode)
Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. (返回指定上下限,預設中點mode的對稱分佈)


>>> random.triangular(0.1, 1.0)
0.8049388820574779

random.betavariate(alpha, beta)
Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1.(返回一個Bata分佈)
random.expovariate(lambd)
Exponential distribution. (返回一個指數分佈)


>>> expovariate(1 / 5)                   # Interval between arrivals averaging 5 seconds
5.148957571865031

random.gammavariate(alpha, beta)
Gamma分佈,alpha > 0 和beta > 0.
從指定的Gamma分佈中隨機返回一個數
random.gauss(mu, sigma)
從指定的Gauss分佈中隨機返回一個數
random.lognormvariate(mu, sigma)
從指定的對數高斯分佈中隨機返回一個數,sigma>0
random.normalvariate(mu, sigma)
從指定的正態分佈中隨機返回一個數


>>> random.gauss(0, 1)
0.5188039605184929
>>> random.lognormvariate(0, 1)
1.466980559247035
>>> random.normalvariate(0, 1)
-1.2096733604207723

random.vonmisesvariate(mu, kappa)
從指定的vonmises分佈中隨機返回一個數
mu 在0~2*pi, 集中引數 kappa >= 0, kappa = 0時, 等價於random.uniform().
random.paretovariate(alpha)
從指定的帕雷託分佈中隨機返回一個數)
random.weibullvariate(alpha, beta)
Weibull distribution. alpha is the scale parameter and beta is the shape parameter.(從指定的威布林分佈中返回一個數)

2. 例項

(1) 隨機序列的生成例子

>>> import random
>>> s = [x for x in range(0, 10)]
>>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(s)
>>> s
[8, 4, 1, 5, 2, 0, 7, 6, 9, 3]

# 生成一個【0,10】長度為100的隨機序列
>>> random_int_list = []
>>> for _ in range(100):
...     random_int_list.append(random.randint(0, 10))
... 
>>> random_int_list
[5, 4, 8, 0, 5, 3, 7, 7, 9, 10, 0, 8, 9, 5, 3, 9, 2, 9, 7, 5, 4, 6, 3, 1, 10, 10, 6, 10, 7, 8, 0, 10, 7, 8, 0, 9, 2, 1, 10, 6, 4, 10, 4, 3, 10, 4, 5, 7, 6, 10, 7, 5, 4, 4, 2, 7, 2, 3, 3, 1, 10, 10, 3, 2, 7, 8, 2, 0, 1, 4, 10, 9, 4, 10, 2, 6, 7, 10, 0, 5, 4, 0, 4, 10, 0, 5, 1, 3, 6, 6, 3, 0, 0, 5, 2, 9, 7, 3, 3, 9]
>>> 

(2) 生成當前時間相關隨機數

from datetime import *
import random

for i in range(0, 1):
    nowTime = datetime.now().strftime("%Y%m%d%H%M%S")  # 生成當前的時間
    randomNum = random.randint(0, 100)  # 生成隨機數n,其中0<=n<=100
    if randomNum <= 10:
        randomNum = str(0) + str(randomNum)
    uniqueNum = str(nowTime) + str(randomNum)
    print(uniqueNum)

出自yongh701:Python 利用當前時間、隨機數產生一個唯一的數字
https://blog.csdn.net/yongh701/article/details/46912391

3. Numpy中的隨機數生成

(1)生成隨機整數

>>> import numpy as np
>>> np.random.random(1)
array([0.42426594])
>>> np.random.random(10)
array([0.36304824, 0.80458524, 0.0056266 , 0.97748616, 0.91748893,
       0.79876095, 0.0248794 , 0.10963302, 0.29487573, 0.79505157])

(2) 指定範圍的整數序列

>>> import numpy as np
>>> np.random.randint(0,10)
 8
>>> np.random.randint(0,10,8)
array([4, 1, 6, 8, 4, 1, 1, 2])

更多可以參考:

python numpy 常用隨機數的產生方法
https://blog.csdn.net/m0_37804518/article/details/78490709
numpy中的隨機數模組
https://www.cnblogs.com/td15980891505/p/6198036.html