标准库random
pseudo-random number generators for various distributions.
Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0).
Python uses the Mersenne Twister as the core generator.
The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module.
The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class.
Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the random(), seed(), getstate(), and setstate() methods.
seed: 当设置相同的seed时,可以得到相同的随机数。
random.seed(1)
a2 = random.random()
print(a2) random.seed(0)
a11 = random.random()
print(a11 == a1) result:
0.8444218515250481
0.13436424411240122
True
getstate:
Return an object capturing the current internal state of the generator. This object can be passed to setstate() to restore the state.
从下面的结果来看,可能和seed有关。
s1 = random.getstate() # a tuple of length 3
print(len(s1[1]), s1)
random.seed(0)
a1 = random.random()
s2 = random.getstate()
print(len(s2[1]), s2) random.seed(1)
a2 = random.random()
s3 = random.getstate()
print(len(s3[1]), s3) random.seed(0)
a11 = random.random()
s4 = random.getstate()
print(len(s4[1]), s4)
print(s4 == s2) result:
625 (3, (2147483648, ..., 3028008404, 624), None)
625 (3, (1372342863, ..., 418789356, 2), None)
625 (3, (2145931878, ..., 3656373148, 2), None)
625 (3, (1372342863, ..., 418789356, 2), None)
True
setstate: 貌似功能与seed一样,都是到达某一状态。
random.seed(0)
s1 = random.getstate()
a1 = random.random()
s2 = random.getstate()
print(a1, s2 == s1) # s2 != s1, 因为生成了一次随机数,状态变了 random.seed(1)
a2 = random.random()
s3 = random.getstate()
print(s3 == s2) # False # random.seed(0)
random.setstate(s1) # 设置为s1才能使a11 == a1, 和s2状态不同。有点像翻书的过程,翻到那一页,首先看到的内容总是一样的。
s4 = random.getstate()
print(s4 == s1) # True
a11 = random.random()
s5 = random.getstate()
print(a11 == a1, s5 == s2) # True True 在s4 == s1的状态下,执行一个相同操作,执行后的状态也相同。
getrandbits:
Returns a Python integer with k random bits. This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. When available, getrandbits() enables randrange() to handle arbitrarily large ranges.
k random bits
is supplied with
k = random.getrandbits(1) # 0、1
k = random.getrandbits(2) # 0、1、2、3
k = random.getrandbits(3) # 0、1、2、3、4、5、6、7
print(k)
Functions for integers
randrange:
This is equivalent to choice(range(start, stop, step)).
Keyword arguments should not be used because the function may use them in unexpected ways.
randrange() is more sophisticated about producing equally distributed values. 【Formerly it used a style like int(random()*n) which could produce slightly uneven distributions.】
r = random.randrange(2, 5)
c = random.choice(range(2, 5))
print(c)
randint(a, b):
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
Functions for sequences
choice(seq):
arg is a seq.
If seq is empty, raises IndexError.
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.
If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()). For example, the relative weights [10, 5, 30, 5] are equivalent to the cumulative weights [10, 15, 45, 50]. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
If neither weights nor cum_weights are specified, selections are made with equal probability(从这点看来,前面的权重指的是某数值被选中的概率). If a weights sequence is supplied, it must be the same length as the population sequence. It is a TypeError to specify both weights and cum_weights.
cs = random.choices([1, 3, 5, 7, 9], weights=[8, 6, 4, 2, 5], k=2)
print(cs) # with replacement, [3, 3]
shuffle(x[, random]):
Shuffle the sequence.
The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().
To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.
l = [1, 3, 5, 7, 9, 3]
s = random.shuffle(l) # 修改序列本身,所以参数必须是可变类型。
print(l, s)
sample(population, k):
Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged.
Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
To choose a sample from a range of integers, use a range() object as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), k=60).
If the sample size is larger than the population size, a ValueError is raised.
# l = (1, 3, 5, 7, 9, 3)
l = [1, 3, 5, 7, 9, 3] #可变类型也可
s = random.sample(l, 2)
print(l, s) # (1, 3, 5, 7, 9, 3) [9, 1]
Real-valued distributions
random(): Return the next random floating point number in the range [0.0, 1.0).
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.
equation:
return a + (b-a) * self.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. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.
gauss(mu, sigma):
Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function.
标准库random的更多相关文章
- Python基础--人们一些最爱的标准库(random time)
Python继续! random 包括返回随机数的函数. 这里跟C++一样,产生的是伪随机数,并非全然随机数. random中一些重要的函数: random() 返回0<n<=1的随机数n ...
- Python标准库---random模块的使用
更新时间:2019.09.12(更新目录) 目录 1. 谈谈随机数 2. random模块 2.1 random.seed() 2.2 random.random() 2.3 random ...
- Python标准库Random
基本方法 获取一个[0,1)的随机浮点数: import random print(random.random()) #输出 0.6701488343121276 获取指定区间的随机浮点数: impo ...
- Python标准库12 数学与随机数 (math包,random包)
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 我们已经在Python运算中看到Python最基本的数学运算功能.此外,math包 ...
- python标准库总的random函数用法
Python标准库中的random函数,可以生成随机浮点数.整数.字符串,甚至帮助你随机选择列表序列中的一个元素,打乱一组数据等.random中的一些重要函数的用法:1 ).random() 返回0& ...
- python标准库介绍——27 random 模块详解
==random 模块== "Anyone who considers arithmetical methods of producing random digits is, of cour ...
- python常用标准库(math数学模块和random随机模块)
常用的标准库 数学模块 import math ceil -- 上取整 对一个数向上取整(进一法),取相邻最近的两个整数的最大值. import math res = math.ceil(4.1) p ...
- python学习笔记系列----(八)python常用的标准库
终于学到了python手册的最后一部分:常用标准库.这部分内容主要就是介绍了一些基础的常用的基础库,可以大概了解下,在以后真正使用的时候也能想起来再拿出来用. 8.1 操作系统接口模块:OS OS模块 ...
- windows下的c语言和linux 下的c语言以及C标准库和系统API
1.引出我们的问题? 标准c库都是一样的!大家想必都在windows下做过文件编程,在linux下也是一样的函数名,参数都一样.当时就有了疑问,因为我们非常清楚 其本质是不可能一样的,源于这是俩个操作 ...
随机推荐
- stingray中使用angularjs
引入angularjs 手动启用angularjs 不使用ng-app, 在所有模块和controller定义后挂载启用angularjs function OnLoad() { scroll(0, ...
- 启动Jupyter Notebook
按照图所示,在命令下输入ipython notebook 即可启动Jupyter. 启动后的效果:
- 如何清空iframe中的内容?
我都是用这种方法往iframe里面添加内容的. document.frames["iframe1"].document.write("<img src='loadi ...
- 五种常见的ASP.NET安全缺陷
保证应用程序的安全应当从编写第一行代码的时候开始做起,原因很简单,随着应用规模的发展,修补安全漏洞所需的代价也随之快速增长.根据IBM的系统科学协会(SystemsSciencesInstitute) ...
- hihocoder第237周:三等分带权树
题目链接 问题描述 给定一棵树,树中每个结点权值为[-100,100]之间的整数.树中包含结点总数不超过1e5.任选两个非根节点A.B,将这两个结点与其父节点断开,可以得到三棵子树.现要求三棵子树的权 ...
- C#通过DSOFile读取与修改文件的属性
搜了一圈用C#读取与修改文件属性的文章,结果几乎找不到- -: 偶然间看到一个DSOFile工具,然后找到了对该工具进行详细讲解的一篇文章:<DSOfile,一个修改windows系统文件摘要的 ...
- 第三部分:Android 应用程序接口指南---第五节:计算---第一章 RenderScript
第1章 RenderScript RenderScript提供一个独立于平台并在本地运行的计算引擎,用它来加速你需要大量计算能力的应用.RenderScript是一个运行与Android上计算密集型的 ...
- 如何让vue文件中的代码在Sublime Text 3中高亮和智能提示
大家写在Sublime Text 3中编写vue文件时,会发现没有代码智能提示,清一色的黑底白字,不会像html.js一样变成彩色,给我们带来了很大的不便.所以需要安装一款叫作Vue Syntax H ...
- 在webpack中使用postcss-px2rem的
经过一番折腾重要搞定了. 首先需要安装postcss-plugin-px2rem. npm install --save-dev postcss-plugin-px2rem 我的webpack工程中没 ...
- ORA-03297: 文件包含在请求的 RESIZE 值以外使用的数据
本文中的45,对应 修改数据文件大小 里面的45 1.移动表前先对表空间做整理 alter tablespace data_cis_test coalesce; 2.在dba_extents找到与ID ...