iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python3 Random模块代码详解
  • 773
分享到

Python3 Random模块代码详解

详解模块代码 2022-06-04 19:06:55 773人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

描述 random() 方法返回随机生成的一个实数,它在[0,1)范围内。 import random help(random) FUNCTioNS betavariate(alpha, beta

描述

random() 方法返回随机生成的一个实数,它在[0,1)范围内。


import random
help(random)
FUNCTioNS
  betavariate(alpha, beta) method of Random instance # 随机实例的方法
    Beta distribution. # β分布
    
    Conditions on the parameters are alpha > 0 and beta > 0. # 必须传入大于0的alpha 与beta参数
    Returned values range between 0 and 1. # 返回一个0 -1 之间的值,这个值你是随机的!
    a = random.betavariate(999999, 99999999999999999) # 第一次执行结果:9.995974671839104e-12 第二次执行结果:1.0006927848540756e-11
    贝塔分布(Beta Distribution) 是一个作为伯努利分布和二项式分布的共轭先验分布的密度函数,在机器学习和数理统计学中有重要应用。
    在概率论中,贝塔分布,也称Β分布,是指一组定义在(0,1) 区间的连续概率分布。
  
  choice(seq) method of Random instance
    Choose a random element from a non-empty sequence. # 随机从一个不为空的序列中取出一个元素,参数必须不为空
    python包含 6 种内建的序列,包括列表、元组、字符串、Unicode字符串、buffer对象和xrange对象。
  
  choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance # 随机实例的方法
    Return a k sized list of population elements chosen with replacement. # 通过chosen with replacement(就是每次抽取的机会都是相同的或按权重来的,前面的选择不会影响后面选择的概率)的方式获取一个由k个元素组成的随机列表
    
    If the relative weights or cumulative weights are not specified, # 如果未指定相对权重或累积权重,
    the selections are made with equal probability.          # 则选择的概率相等。
    从population中随机抽取k个元素(可重复)。两个参数不能同时存在。
    示例:
    print(random.choices(['red', 'black', 'green'], [18, 18, 2], k=6) ) # 以18的概率权重取red,18的概率权重取black,2的概率权重取green,共进行6次
    
    trial = lambda: random.choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5 # H的概率是0.6,T的概率是0.4
    print(sum(trial() for i in range(10000)) / 10000)

    trial2 = lambda : 2500 <= sorted(random.choices(range(10000), k=5))[2] < 7500
    print(sum(trial2() for i in range(10000)) / 10000 )

    from statistics import mean
    data = 1, 2, 4, 4, 10
    means = sorted(mean(random.choices(data, k=5)) for i in range(20)) # mean是求平均
    print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' 
   f'interval from {means[1]:.1f} to {means[-2]:.1f}') # 这里的f用法 
    # 上面程序的三次执行结果分别是:
    # The sample mean of 4.2 has a 90% confidence interval from 2.4 to 6.6
    # The sample mean of 4.2 has a 90% confidence interval from 2.6 to 7.2
    # The sample mean of 4.2 has a 90% confidence interval from 2.0 to 7.0

  expovariate(lambd) method of Random instance # 随机实例的方法
    Exponential distribution. # 指数分布
    
    lambd is 1.0 divided by the desired mean. It should be
    nonzero. (The parameter would be called "lambda", but that is
    a reserved Word in Python.) Returned values range from 0 to
    positive infinity if lambd is positive, and from negative
    infinity to 0 if lambd is negative.
    λ(lambd)是1除以所需数的,它不能为零。(参数应当被称为lambda,但那是python保留字)
    这个函数返回一个0到正无穷大的随机数(如果 λ 为正),或返回一个负无穷大到0的随机数,如果(如果 λ 为负)
  
  gammavariate(alpha, beta) method of Random instance # 随机实例的方法
    Gamma distribution. Not the gamma function! # 伽玛分布.不是gamma函数
    
    Conditions on the parameters are alpha > 0 and beta > 0. # 参数的条件是两个参数都要大于0
    
    The probability distribution function is: # 概率分布函数为:
    
          x ** (alpha - 1) * math.exp(-x / beta)
     pdf(x) = --------------------------------------
           math.gamma(alpha) * beta ** alpha
  
  gauss(mu, sigma) method of Random instance # 随机实例的方法
    Gaussian distribution. # 高斯分布,又名正态分布或常态分布
    
    mu is the mean, and sigma is the standard deviation. This is 
    slightly faster than the nORMalvariate() function.
    
    Not thread-safe without a lock around calls.
    # mu为期望,sigma为方差,这个函数比normalvariate()函数速度要快一点点
    # 没有线程调用,线程不安全。
    # 有两个必传参数,mu与sigma,
  
  getrandbits(...) method of Random instance # 随机实例的方法
    getrandbits(k) -> x. Generates an int with k random bits. # 以整型形式返回k个随机位(二进制数)。如果处理的是真正的随机事务(比如加密),这个函数尤为有用。
  
  getstate() method of Random instance # 随机实例的方法
    Return internal state; can be passed to setstate() later. # 返回捕获当前生成器内部状态的对象.该对象可以用于函数setstate()来保存当前的状态.
  
  lognormvariate(mu, sigma) method of Random instance # 随机实例的方法
    Log normal distribution.
    对数正态分布(logarithmic normal distribution)是指一个随机变量的对数服从正态分布,则该随机变量服从对数正态分布。
    对数正态分布从短期来看,与正态分布非常接近。但长期来看,对数正态分布向上分布的数值更多一些。
    
    If you take the natural logarithm of this distribution, you'll get a
    normal distribution with mean mu and standard deviation sigma.
    mu can have any value, and sigma must be greater than zero.
    # 如果你对这个分布的参数取自然对数,你会得到一个均数为mu,标准差为sigma的正态分布。
    # mu参数可是任何值,sigma参数必须大于0
  
  normalvariate(mu, sigma) method of Random instance # 随机实例的方法
    Normal distribution. # 常态分布,又名正态分布和高斯分布
    
    mu is the mean, and sigma is the standard deviation. # mu为期望,sigma为方差
  
  paretovariate(alpha) method of Random instance # 随机实例的方法
    Pareto distribution. alpha is the shape parameter. # 帕累托分布;参数alpha为形状参数
    # 帕累托分布(Pareto distribution)是以意大利经济学家维弗雷多·帕雷托命名的, 是从大量真实世界的现象中发现的幂次定律分布,
    # 这个分布在经济学以外,也被称为布拉德福分布。帕累托因对意大利20%的人口拥有80%的财产的观察而著名,后来被约瑟夫·朱兰和
    # 其他人概括为帕累托法则(80/20法则),后来进一步概括为帕累托分布的概念。

  
  randint(a, b) method of Random instance # 随机实例的方法
    Return random integer in range [a, b], including both end points. # 返回a到b之间的一个随机整数,可取中a和b
    # 必须传入两个参数,且a, b都必须是整数,可以为负整数,a参数必须小于等于b参数。
  
  random(...) method of Random instance # 随机实例的方法
    random() -> x in the interval [0, 1). # 无参数,生成一个0-1之间的随机数,可以是0,但不会生成1
  
  randrange(start, stop=None, step=1, _int=<class 'int'>) method of Random instance # 随机实例的方法
    Choose a random item from range(start, stop[, step]). # 随机从一个范围中选取一个参数
    
    This fixes the problem with randint() which includes the # 这个函数修复了randint()中能取到范围右边的数字的情况
    endpoint; in Python this is usually not what you want.  # randint()可以取到右边范围数字的情况通常是很多人不愿意看到的
    参数必须为整数,start要小于stop参数
  
  sample(population, k) method of Random instance # 随机实例的方法
    Chooses k unique random elements from a population sequence or set. # 从一个population序列或集合中取出k个随机元素
    
    Returns a new list containing elements from the population while  # 返还一个包含上述元素的列表,原序列或集合不会改变。
    leaving the original population unchanged. The resulting list is 
    in selection order so that all sub-slices will also be valid random # 返还的列表是按挑选的先后顺序排列的。这样的话,所有子切片也将是合法的随机样本。
    samples. This allows raffle winners (the sample) to be partitioned # 这样做允许样本中的被选中的幸运儿能按第一名第二名这样的顺序排列(在返还的列表中)
    into grand prize and second place winners (the subslices).
    
    Members of the population need not be hashable or unique. If the  # population序列中的成员不需要是可哈希的或者是不重样的。
    population contains repeats, then each occurrence is a possible   # 如果population序列包含重复的成员,那么每次的选取都会是样本中可能的选择
    selection in the sample.
    
    To choose a sample in a range of integers, use range as an argument # 为了在一个整数范围内选择一个样本,请使用范围值作为一个参数。
    This is especially fast and space efficient for sampling from a   # 当从庞大数据中取样时这样做将会非常快速并且节省内存
    large population:  sample(range(10000000), 60)           # 示例:sample(range(10000000), 60)
  
  seed(a=None, version=2) method of Random instance # 随机实例的方法
    Initialize internal state from hashable object.          # 通过可哈希对象初始化内部状态
    
    None or no argument seeds from current time or from an operating # 参数为None或无参数的情况下,则seeds根据当前时间来自己选择这个值
    system specific randomness source if available.          # 或从系统特定的随机性源中取值(如果条件可行)
    
    If *a* is an int, all bits are used.               # 如果参数a为整型,所有的bits位都将被使用
    
    For version 2 (the default), all of the bits are used if *a* is a str, # 当version参数为2(默认参数),如果参数a是一个字符串类型,bytes或bytearray,则所有的bits位都将被使用
    bytes, or bytearray. For version 1 (provided for reproducing random  # 当version参数为1时(提供从老版本python中重新生成的随机序列)
    sequences from older versions of Python), the alGorithm for str and   # 通过对str,bytes的算法生成一个窄范围的种子。
    bytes generates a narrower range of seeds.
  
  setstate(state) method of Random instance # 随机实例的方法
    Restore internal state from object returned by getstate(). # 保存getstate()取得并返回的对象。
  
  shuffle(x, random=None) method of Random instance # 随机实例的方法
    Shuffle list x in place, and return None. # 打乱列表x并返回None x为必传列表参数
    
    Optional argument random is a 0-argument function returning a # 可选参数为一个不需参数的返回0-1之间浮点数的函数
    random float in [0.0, 1.0); if it is the default None, the   # 如果可选参数为默认的None,则它会使用random.random函数方法
    standard random.random will be used.
    如果你有一个更好的随机数生成器,或者说你有一个适合自己应用的随机数发生器,那么你就可以使用它而不是使用系统默认那个。
  
  triangular(low=0.0, high=1.0, mode=None) method of Random instance # 随机实例的方法
    Triangular distribution. # 三角分布(triangular distribution),亦称辛普森分布或三角形分布
    
    Continuous distribution bounded by given lower and upper limits, # 三角形分布是低限为low、上限为high、众数默认为两者平均数的连续概率分布。
    and having a given mode value in-between.
    
    Http://en.wikipedia.org/wiki/Triangular_distribution
  
  uniform(a, b) method of Random instance # 随机实例的方法
    Get a random number in the range [a, b) or [a, b] depending on rounding. # 从a与b之间取一个随机数,一定可以取到a,b能否取到看b的舍入
    a b两个参数必须有,可为整型可为浮点型,目前本人知道的取到b的方法的用math.ceil
    这个方法返回的是一个随机数
  
  vonmisesvariate(mu, kappa) method of Random instance # 随机实例的方法
    Circular data distribution. # 循环数据分布或冯·米塞斯分布
    
    mu is the mean angle, expressed in radians between 0 and 2*pi, and
    kappa is the concentration parameter, which must be greater than or
    equal to zero. If kappa is equal to zero, this distribution reduces
    to a uniform random angle over the range 0 to 2*pi.
    # mu 是位置的度量,它的聚会在0-2*pi之间,kappa是集中度的度量,它必须大于或等于0。
    # 如果kappa等于0,这个分布是均匀分布,对于κ很小的情形,分布近似均匀分布,其位置度量在0-2*pi之间

  
  weibullvariate(alpha, beta) method of Random instance
    Weibull distribution. # 韦布尔分布
    
    alpha is the scale parameter and beta is the shape parameter. # λ>0是比例参数(scale parameter),k>0是形状参数(shape parameter)
    # 在这里alpha是比例参数,beta是形状参数
    威布尔分布(Weibull distribution),又称韦伯分布或韦布尔分布,是可靠性分析和寿命检验的理论基础。
    威布尔分布:在可靠性工程中被广泛应用,尤其适用于机电类产品的磨损累计失效的分布形式。由于它可以利用概率值很容易地推断出它的分布参数,
    被广泛应用于各种寿命试验的数据处理。

总结

以上就是本文关于python3 Random模块代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

--结束END--

本文标题: Python3 Random模块代码详解

本文链接: https://www.lsjlt.com/news/15809.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python3 中 random模块
    Python中的random模块用于生成随机数。 下面具体介绍random模块的功能: #用于生成一个0到1的 随机浮点数:0<= n < 1.0 import random a = random.random() pri...
    99+
    2023-01-31
    模块 random
  • python3 时间模块 random模
    话不多说,一个是算时间的,还有一个是生成验证码的  1 #!usr/bin/env/ python 2 # -*- coding:utf-8 -*- 3 # Author: XiaoFeng 4 import time 5 s...
    99+
    2023-01-31
    模块 时间 random
  • python3--模块collections,time,random,sys
    defaultdict(默认字典)有如下值集合[11,22,33,44,55,66,77,88,99,90......],将所有大于66的值保存至字典的第一个key中,小于66的值保存至第二个key的值中即:{'k1':大于...
    99+
    2023-01-30
    模块 collections sys
  • Python的random模块详解
    目录 1.random()函数 2.randint(a, b)函数 3.uniform(a, b)函数 4.choice(seq)函数 5.shuffle(seq)函数 6.sample(seq, k)函数 7.randrange([sta...
    99+
    2023-10-20
    python numpy 数据分析
  • python的random和time模块详解
    目录一、模块概述二、模块内容三、模块导入的原理四、模块导入的方法五、random模块六、time模块(1)python表示时间的三种格式(2)常用方法:(3)时间元组、时间戳、格式化...
    99+
    2024-04-02
  • python random模块的详细讲解
    1.random()方法random.random()方法返回的是[0,1)之间的浮点数 >>> import random c = random.random()print c 0.311067669783 ...
    99+
    2023-01-31
    模块 详细 python
  • Python伪随机数模块random详解
    目录random模块random.seed常用整数随机函数常用序列随机函数常用实数随机函数总结random模块 该模块实现了各种分布的伪随机数生成器。(包括在实数轴上计算均匀、正态(...
    99+
    2024-04-02
  • 详解python代码模块化
    一、概念 1、模块化代码可以使代码易于维护和调试,并且提高代码的重用性; 2、函数可以用来减少冗余的代码并提高代码的可重用性。函数也可以用来模块化代码并提高程序的质量; 3、在pyt...
    99+
    2024-04-02
  • Python3内置json模块编码解码方法详解
    目录JSON简介dumps编码编码字典编码列表编码字符串格式化输出JSON转换关系对照表loads解码总结JSON简介 JSON(JavaScript Object Notation...
    99+
    2024-04-02
  • Python学习之随机模块random详解
    目录random.random()random.uniform()random.randint()random.choice()random.sample()random.randr...
    99+
    2024-04-02
  • Spring中MVC模块代码详解
    SpringMVC的Controller用于处理用户的请求。Controller相当于Struts1里的Action,他们的实现机制、运行原理都类似Controller是个接口,一般直接继承AbstrcatController,并实现han...
    99+
    2023-05-30
    springmvc 多模块 sprin
  • Spring之ORM模块代码详解
    Spring框架七大模块简单介绍Spring中MVC模块代码详解ORM模块对Hibernate、JDO、TopLinkiBatis等ORM框架提供支持ORM模块依赖于dom4j.jar、antlr.jar等包在Spring里,Hiberna...
    99+
    2023-05-30
    spring orm 框架
  • Python3 pickle模块的使用详解
    pickle模块是Python标准库中的一个模块,用于序列化和反序列化Python对象。它可以将对象转换为字节流,然后可以将字节流保...
    99+
    2023-10-11
    python
  • Python标准库之Math,Random模块使用详解
    目录数学模块ceil -- 上取整floor -- 下取整四舍五入pow -- 幂运算sqrt -- 开平方运算fabs -- 绝对值modf -- 拆分整数小数copysign -...
    99+
    2024-04-02
  • Python3 json模块之编码解码方法讲解
    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,这些特性使J...
    99+
    2024-04-02
  • python3 time模块解释
    time() 模块继承自 Object 类,datetime() 模块继承自 Object 下面的 Date() 模块。 time 提供的功能更加接近于操作系统层面,其所能表述的日期范围被限定在 1970 - 2038 之间,如...
    99+
    2023-01-31
    模块 time
  • 如何使用random模块生成验证码
    这篇“如何使用random模块生成验证码”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“如何...
    99+
    2024-04-02
  • Python3内置模块中base64的解码方法
    这篇文章给大家介绍Python3内置模块中base64的解码方法,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。即 base64 其实不能归属密码领域,作用也不是用于加密,它是一种编码算法,但是具有不可读性,所以可以说是...
    99+
    2023-06-02
  • #6 ipdb模块源代码解读
    前言 好久不见,大家最近可好。通过前几节的学习,相信你已经掌握了面向对象的大量知识,但是光知道是不够的,需要自己多写、多看,学一门语言无非不过这两种秘诀嘛。因此本篇博文带着大家剖析一次源代码,剖析对象为代码调试模块:ipdb。为什么选择这...
    99+
    2023-01-30
    源代码 模块 ipdb
  • Python 的Json 模块编码详解
    可以用函数 json.dumps()将 Python 对象编码转换为字符串形式。 例如: import json python_obj = [[1,2,3],3.14,'abc...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作