Python3 Random模块代码详解


Posted in Python onDecember 04, 2017

描述

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模块代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
Python实现动态加载模块、类、函数的方法分析
Jul 18 Python
pyqt5的QComboBox 使用模板的具体方法
Sep 06 Python
python取数作为临时极大值(极小值)的方法
Oct 15 Python
python3 实现对图片进行局部切割的方法
Dec 05 Python
代码详解django中数据库设置
Jan 28 Python
在python里协程使用同步锁Lock的实例
Feb 19 Python
详解Python:面向对象编程
Apr 10 Python
Python线上环境使用日志的及配置文件
Jul 28 Python
Pytorch mask-rcnn 实现细节分享
Jun 24 Python
详解KMP算法以及python如何实现
Sep 18 Python
Python控制台输出俄罗斯方块移动和旋转功能
Apr 18 Python
使用tensorflow 实现反向传播求导
May 26 Python
利用python爬取斗鱼app中照片方法实例
Dec 03 #Python
CentOS 6.5中安装Python 3.6.2的方法步骤
Dec 03 #Python
python3利用smtplib通过qq邮箱发送邮件方法示例
Dec 03 #Python
Python中类的初始化特殊方法
Dec 01 #Python
Python抓取框架Scrapy爬虫入门:页面提取
Dec 01 #Python
Python实现调度算法代码详解
Dec 01 #Python
Python进阶学习之特殊方法实例详析
Dec 01 #Python
You might like
优化php效率,提高php性能的一些方法
2011/03/24 PHP
解析关于wamp启动是80端口被占用的问题
2013/06/21 PHP
PHP+javascript制作带提示的验证码源码分享
2014/05/28 PHP
功能强大的PHP POST提交数据类
2016/07/15 PHP
使用PHPMailer发送邮件实例
2017/02/15 PHP
JavaScript实现动态增加文件域表单
2009/02/12 Javascript
Javascript类库的顶层对象名用户体验分析
2010/10/24 Javascript
jQuery is()函数用法3例
2014/05/06 Javascript
node.js中的url.format方法使用说明
2014/12/10 Javascript
Node.js开发之访问Redis数据库教程
2015/01/14 Javascript
JS实现在网页中弹出一个输入框的方法
2015/03/03 Javascript
JS实现的表格行上下移动操作示例
2016/08/03 Javascript
原生和jQuery的ajax用法详解
2017/01/23 Javascript
Angular 4依赖注入学习教程之ClassProvider的使用(三)
2017/06/04 Javascript
详解vue-router和vue-cli以及组件之间的传值
2017/07/04 Javascript
javaScript和jQuery自动加载简单代码实现方法
2017/11/24 jQuery
webpack4+Vue搭建自己的Vue-cli项目过程分享
2018/08/29 Javascript
webpack配置proxyTable时pathRewrite无效的解决方法
2018/12/13 Javascript
[02:50]【扭转乾坤,只此一招】DOTA2永雾林渊版本开启新篇章
2020/12/22 DOTA
Python黑魔法@property装饰器的使用技巧解析
2016/06/16 Python
python用模块zlib压缩与解压字符串和文件的方法
2016/12/16 Python
python下setuptools的安装详解及No module named setuptools的解决方法
2017/07/06 Python
python如何通过实例方法名字调用方法
2018/03/21 Python
Python数据分析库pandas基本操作方法
2018/04/08 Python
python邮件发送smtplib使用详解
2020/06/16 Python
浅谈关于Python3中venv虚拟环境
2018/08/01 Python
详解python中递归函数
2019/04/16 Python
使用matlab或python将txt文件转为excel表格
2019/11/01 Python
瑜伽国际:Yoga International
2018/04/18 全球购物
俄罗斯购买剧院和演唱会门票网站:Parter.ru
2019/11/09 全球购物
如何获取某个日期是当月的最后一天
2013/12/05 面试题
材料加工工程求职信
2014/02/19 职场文书
金融系应届毕业生求职信
2014/05/26 职场文书
高中班级口号
2014/06/09 职场文书
中班下学期个人工作总结
2015/02/12 职场文书
Python带你从浅入深探究Tuple(基础篇)
2021/05/15 Python