>


一、Python标准库中的random函数

import random

1.random.random()

用于生成一个0到1的随机浮点数: 0 <= n < 1.0

2.random.randint(start,stop)

随机生成[start,stop]区间内的整数

3.random.uniform(start,stop)

填补random()的缺陷,可以设置两个参数,下限和上限,生成区间内的分数

4.random.choice(series)

从序列中返回一个任意的元素,series可为字符串、列表、元组

5.random.sample(series,num)

从序列series中返回任意num个元素,返回一个序列

6. random.shuffle(series)

将序列的所有元素打乱

7.random.randrange (start,stop ,step)

返回区间[start,stop)按指定递增基数step集合中的一个随机数,基数缺省值为1。
例如,random.randrange (0, 20 ,5)
[0,20)按基数为5递增的集合为[0,5,10,15],在该集合中随机取一个数
代码示例:

import random
## 生成一个0到1的随机浮点数
random.random()
## Out[1]:0.09706381980481515

## 生成[1,4]区间内的整数
random.randint(1,4)
## Out[2]:2

## 生成[1,4]区间内的分数
random.uniform(1,4)
## Out[3]:3.9569812254916856

## 从序列中返回一个任意的元素
random.choice([1,2,3,4])
## Out[4]:2

## 从序列series中返回任意2个元素
random.sample([1,2,3,4],2)
## Out[5]:[2, 3]

## 将序列的所有元素打乱
list = [1,2,3,4]
random.shuffle(list)
list
## Out[6]:[3, 1, 4, 2]

## 返回区间[0,20)按指定递增基数5集合中的一个随机数
random.randrange (0,20,5)
## Out[7]:10

二、Python标准库中的numpy函数

import numpy as np
随机数生成模块numpy.random

1.生成器

种随机数种子,根据同一种子产生的随机数是相同的
定义全局种子:seed([seed]),参数为整数或者矩阵
代码示例:

import numpy as np
np.random.seed(123) #设置随机种子为123

2.简单随机数

产生简单的随机数据,可以是任何维度
代码示例:

import numpy as np
## 产生2行3列均匀分布随机数组
np.random.rand(2,3)
## Out[8]:array([[0.64783015, 0.74924762, 0.12333907],
##               [0.44305453, 0.62676146, 0.17366148]])

## 3行3列正态分布随机数据
np.random.randn(3,3) 
## Out[9]:array([[ 0.46551625,  0.41251493,  0.1223511 ],
##               [-0.58531667, -0.0187292 , -0.62425071],
##               [-0.33741965, -0.06341708, -0.38698573]]),

## (1,10)以内的5行5列随机整数
np.random.randint(1,10,[5,5]) 
## Out[10]:array([[5, 1, 1, 9, 8],
##                [4, 8, 5, 4, 7],
##                [9, 4, 4, 5, 3],
##                [2, 5, 9, 8, 7],
##                [3, 3, 1, 3, 5]])

## (0,1)以内10个随机浮点数
np.random.random(10)
## Out[11]:array([0.23234971, 0.18586494, 0.15506408, 0.69217427, 0.13629773,
##                0.30373232, 0.25942041, 0.43554809, 0.68500132, 0.12891991])

## [0,10)内随机选择一个数
np.random.choice(10) 
## Out[12]:4

3.分布

产生指定分布的数据,如高斯分布等

函数名称

函数功能

参数说明

均匀分布

uniform([low, high, size])

low:下界;high:上界;size:返回个数

正态(高斯)分布

normal([loc, scale, size])

loc:均值;scale:标准差

代码示例:

import numpy as np
## 均匀分布
np.random.uniform(low=2,high=4,size=2)
## Out[13]:array([2.09099648, 2.2292535 ])

## 正态分布
np.random.normal(1,3)
## Out[14]:1.2474069345999501

## 正态分布图像
import numpy as np
import matplotlib.pyplot as plt

mu = 1  #期望为1
sigma = 3  #标准差为3
num = 10000  #个数为10000

rand_data = np.random.normal(mu, sigma, num)
count, bins, ignored = plt.hist(rand_data, 30, normed=True)
plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (bins - mu)**2 / (2 * sigma**2)), linewidth=2, color='r')
plt.show()

python 不同随机数 python随机数方法_随机数

4.排列

函数名称

函数功能

参数说明

shuffle(x)

打乱对象x(多维矩阵按照第一维打乱)

矩阵或者列表

permutation(x)

打乱并返回该对象(多维矩阵按照第一维打乱)

整数或者矩阵

代码示例:

## 生成3行4列整数矩阵
rand_data = np.random.randint(1, 10, (3, 4))
rand_data 
## Out[15]:array([[5, 5, 3, 6],
##                [4, 7, 3, 7],
##                [5, 2, 1, 6]])

## shuffle(x)
np.random.shuffle(rand_data)
rand_data
## Out[16]:array([[4, 7, 3, 7],
##                [5, 5, 3, 6],
##                [5, 2, 1, 6]])

## permutation(x)
np.random.permutation(rand_data)
## Out[16]:array([[4, 7, 3, 7],
##                [5, 5, 3, 6],
##                [5, 2, 1, 6]])

三、按照指定概率生成随机数

1.按照指定概率从数字列表中随机抽取数字

代码示例:

import numpy as np
import random
 
# 定义从一个数字列表中以一定的概率取出对应区间中数字的函数
def get_number_by_pro(number_list, pro_list):
    """
    :param number_list:数字列表
    :param pro_list:数字对应的概率列表
    :return:按概率从数字列表中抽取的数字
    """
    # 用均匀分布中的样本值来模拟概率
    x = random.uniform(0, 1)
    # 累积概率
    cum_pro = 0.0
    # 将可迭代对象打包成元组列表
    for number, number_pro in zip(number_list, pro_list):
        cum_pro += number_pro
        if x < cum_pro:
            print("概率为:",x)
            return number
  
  
# 主模块
if __name__ == "__main__":
    # 数字列表
    num_list = [1, 2, 3, 4, 5]
    # 对应的概率列表
    pr_list = [0.1, 0.3, 0.1, 0.4, 0.1]
    # 函数调用
    n = get_number_by_pro(number_list=num_list, pro_list=pr_list)
    print("返回的值为:",n)
## Out[17]:概率为: 0.8595909698867323
##         返回的值为: 4

2.按照指定概率从区间列表中的某个区间内生成随机数

代码示例:

import numpy as np
import random

# 定义从一个数字列表中以一定的概率取出对应区间中数字的函数
def get_number_by_pro(number_list, pro_list):
    """
    :param number_list:数字列表
    :param pro_list:数字对应的概率列表
    :return:按概率从数字列表中抽取的数字
    """
    # 用均匀分布中的样本值来模拟概率
    x = random.uniform(0, 1)
    # 累积概率
    cum_pro = 0.0
    # 将可迭代对象打包成元组列表
    for number, number_pro in zip(number_list, pro_list):
        cum_pro += number_pro
        if x < cum_pro:
            # 从区间[number - 1,number]上随机抽取一个值
            num = np.random.uniform(number - 1,number)
            print("概率为:",x)
            # 返回值
            return num
  
  
# 主模块
if __name__ == "__main__":
    # 数字列表
    num_list = [1, 2, 3, 4, 5]
    # 对应的概率列表
    pr_list = [0.1, 0.3, 0.1, 0.4, 0.1]
    # 函数调用
    n = get_number_by_pro(number_list=num_list, pro_list=pr_list)
    print("返回的值为:",n)
## Out[17]:概率为: 0.21397703796534095
##         返回的值为: 1.707879438208344

3.列表个数较少时,可使用choice

示例:随机生成2或4,2的概率比较大
代码示例:

random.choice([2,2,2,4])


(本文内容根据网络资料整理和来自用户投稿,出于传递更多信息之目的,不代表本站其观点和立场。也不对其真实性、可靠性承担任何法律责任,特此声明!)

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部