Python随机数、随机序列生成

版权声明:欢迎交流学习,转载请注明出处。 https://blog.csdn.net/qq_23869697/article/details/83932327

主要包括两部分,第一部分是对官方文档的简要总结,第二部分是一些实际应用中使用到的随机数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

猜你喜欢

转载自blog.csdn.net/qq_23869697/article/details/83932327