随机数的使用是很多算法的关键步骤,例如蒙特卡洛法、遗传算法中的轮盘赌法的过程,因此对于任意一种语言,掌握其各类型随机数生成的方法至关重要,Python与R在随机数底层生成上都依靠梅森旋转(twister)来生成高质量的随机数,但在语法上存在着很多异同点。

Python

numpy中的random模块

from numpy import random
?random
Type: module
String form: <module 'numpy.random' from 'D:\\anaconda\\lib\\site-packages\\numpy\\random\\__init__.py'>
File: d:\anaconda\lib\site-packages\numpy\random\__init__.py
Docstring:
========================
Random Number Generation
========================
==================== =========================================================
Utility functions
==============================================================================
random_sample Uniformly distributed floats over ``[0, 1)``.
random Alias for `random_sample`.
bytes Uniformly distributed random bytes.
random_integers Uniformly distributed integers in a given range.
permutation Randomly permute a sequence / generate a random sequence.
shuffle Randomly permute a sequence in place.
seed Seed the random number generator.
choice Random sample from 1-D array.
==================== =========================================================
==================== =========================================================
Compatibility functions
==============================================================================
rand Uniformly distributed values.
randn Normally distributed values.
ranf Uniformly distributed floating point numbers.
randint Uniformly distributed integers in a given range.
==================== =========================================================
==================== =========================================================
Univariate distributions
==============================================================================
beta Beta distribution over ``[0, 1]``.
binomial Binomial distribution.
chisquare :math:`\chi^2` distribution.
exponential Exponential distribution.
f F (Fisher-Snedecor) distribution.
gamma Gamma distribution.
geometric Geometric distribution.
gumbel Gumbel distribution.
hypergeometric Hypergeometric distribution.
laplace Laplace distribution.
logistic Logistic distribution.
lognormal Log-normal distribution.
logseries Logarithmic series distribution.
negative_binomial Negative binomial distribution.
noncentral_chisquare Non-central chi-square distribution.
noncentral_f Non-central F distribution.
normal Normal / Gaussian distribution.
pareto Pareto distribution.
poisson Poisson distribution.
power Power distribution.
rayleigh Rayleigh distribution.
triangular Triangular distribution.
uniform Uniform distribution.
vonmises Von Mises circular distribution.
wald Wald (inverse Gaussian) distribution.
weibull Weibull distribution.
zipf Zipf's distribution over ranked data.
==================== =========================================================
==================== =========================================================
Multivariate distributions
==============================================================================
dirichlet Multivariate generalization of Beta distribution.
multinomial Multivariate generalization of the binomial distribution.
multivariate_normal Multivariate generalization of the normal distribution.
==================== =========================================================
==================== =========================================================
Standard distributions
==============================================================================
standard_cauchy Standard Cauchy-Lorentz distribution.
standard_exponential Standard exponential distribution.
standard_gamma Standard Gamma distribution.
standard_normal Standard normal distribution.
standard_t Standard Student's t-distribution.
==================== =========================================================
==================== =========================================================
Internal functions
==============================================================================
get_state Get tuple representing internal state of generator.
set_state Set state of generator.
==================== =========================================================

上述random的模块说明文档详细说明了random中内置的各种随机数生成方法,下面针对其中一些常见的举例说明:

1.random.random_sample()与random.random()

生成[0,1]之间的服从均匀分布的浮点随机数

from numpy import random
for i in range(10):
print(random.random_sample())
0.5131167122678871
0.3182844248720986
0.5391999374256481
0.2212549424277599
0.80648135792427
0.34225462561468434
0.5388888490671446
0.00587378555105833
0.6731524781805254
0.21002426217873815

2.random.random_integers()

生成指定范围内的可重复整数

random.random_integers(1,10,10)
Out[44]: array([ 9, 10, 6, 4, 10, 10, 5, 3, 1, 6])

3.random.permutation()

生成指定范围内所有整数的一次随机排列

for i in range(5):
token = random.permutation(5)
print(token)
print(set(token))
[0 2 1 3 4]
{0, 1, 2, 3, 4}
[0 3 4 2 1]
{0, 1, 2, 3, 4}
[2 3 1 4 0]
{0, 1, 2, 3, 4}
[4 3 0 1 2]
{0, 1, 2, 3, 4}
[1 2 4 0 3]
{0, 1, 2, 3, 4}

4.random.shuffle()

将指定的列表随机打乱顺序

list = [i for i in range(10)]
random.shuffle(list)
print(list)
[6, 8, 2, 4, 5, 3, 0, 7, 1, 9]

5.random.seed()

以括号中的整数为起点设置伪随机数种子,同样的随机数种子设置后生成的随机数相同

random.seed(42)
print(random.permutation(5))
random.seed(42)
print(random.permutation(5))
[1 4 2 0 3]
[1 4 2 0 3]

6.random.choice()

从制定的序列中随机抽取多个元素(有放回或无放回,通过replace参数控制)

list = [i for i in range(10)]
random.choice(list,6,replace=False)#有放回
Out[8]: array([9, 6, 4, 2, 7, 8])
random.choice(list,6,replace=False)#无放回
Out[9]: array([1, 3, 9, 4, 0, 8])

7.random.rand()

生成0-1中服从均匀分布的多个随机数

random.rand(5)
Out[19]: array([0.86317047, 0.43070734, 0.85228662, 0.74797087, 0.76224563])

8.random.randn()

生成多个服从标准正态分布的随机数

random.randn(10)
Out[21]:
array([-0.25617082, -0.85531159, -0.18286371, 1.25656827, -0.72270841,
0.13949334, 0.92318096, -1.12549131, -0.46908035, -0.28388281])

9.random.randint()

等可能的生成指定范围内的多个随机整数

random.randint(1,10,5)
Out[29]: array([2, 9, 8, 8, 9])

R

作为专为统计而生的一种语言,R在随机数生成上自然是异常的丰富,这里仅举常用的一些随机数生成函数

1.rnorm()

生成服从正态分布的随机数,其中参数mean控制均值,sd控制标准差

> rnorm(5,mean=0,sd=1)
[1] -0.36167951 -0.50435239 -0.20245800 0.07877604 0.23662553

2.runif()

生成指定范围内的均匀分布随机数

> runif(5, min=0,max=10)
[1] 3.2774081 1.7341489 8.4128022 3.1511841 0.3385417

3.sample()

以不放回的方式生成指定范围内的随机整数序列

> sample(1:10,5,replace=T)#有放回
[1] 4 9 3 4 4
> sample(1:10,5,replace=F)#无放回
[1] 3 2 6 8 1

4.set.seed()

以括号内的整数值作为随机数发生算法的起点,因此通过控制伪随机数种子的参数,可以实现随机抽样的重现

而真正的随机算法里是默认以系统时间等我们认为充分随机的数字作为起点

> set.seed(42)
> sample(1:10,5,replace=F)
[1] 10 9 3 6 4
> set.seed(42)
> sample(1:10,5,replace=F)
[1] 10 9 3 6 4

(数据科学学习手札03)Python与R在随机数生成上的异同的更多相关文章

  1. (数据科学学习手札58)在R中处理有缺失值数据的高级方法

    一.简介 在实际工作中,遇到数据中带有缺失值是非常常见的现象,简单粗暴的做法如直接删除包含缺失值的记录.删除缺失值比例过大的变量.用0填充缺失值等,但这些做法会很大程度上影响原始数据的分布或者浪费来之 ...

  2. (数据科学学习手札47)基于Python的网络数据采集实战(2)

    一.简介 马上大四了,最近在暑期实习,在数据挖掘的主业之外,也帮助同事做了很多网络数据采集的内容,接下来的数篇文章就将一一罗列出来,来续写几个月前开的这个网络数据采集实战的坑. 二.马蜂窝评论数据采集 ...

  3. (数据科学学习手札80)用Python编写小工具下载OSM路网数据

    本文对应脚本已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 我们平时在数据可视化或空间数据分析的过程中经常会 ...

  4. (数据科学学习手札50)基于Python的网络数据采集-selenium篇(上)

    一.简介 接着几个月之前的(数据科学学习手札31)基于Python的网络数据采集(初级篇),在那篇文章中,我们介绍了关于网络爬虫的基础知识(基本的请求库,基本的解析库,CSS,正则表达式等),在那篇文 ...

  5. (数据科学学习手札32)Python中re模块的详细介绍

    一.简介 关于正则表达式,我在前一篇(数据科学学习手札31)中已经做了详细介绍,本篇将对Python中自带模块re的常用功能进行总结: re作为Python中专为正则表达式相关功能做出支持的模块,提供 ...

  6. (数据科学学习手札90)Python+Kepler.gl轻松制作时间轮播图

    本文示例代码及数据已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 Kepler.gl作为一款强大的开源地理信 ...

  7. (数据科学学习手札55)利用ggthemr来美化ggplot2图像

    一.简介 R中的ggplot2是一个非常强大灵活的数据可视化包,熟悉其绘图规则后便可以自由地生成各种可视化图像,但其默认的色彩和样式在很多时候难免有些过于朴素,本文将要介绍的ggthemr包专门针对原 ...

  8. (数据科学学习手札40)tensorflow实现LSTM时间序列预测

    一.简介 上一篇中我们较为详细地铺垫了关于RNN及其变种LSTM的一些基本知识,也提到了LSTM在时间序列预测上优越的性能,本篇就将对如何利用tensorflow,在实际时间序列预测任务中搭建模型来完 ...

  9. (数据科学学习手札69)详解pandas中的map、apply、applymap、groupby、agg

    *从本篇开始所有文章的数据和代码都已上传至我的github仓库:https://github.com/CNFeffery/DataScienceStudyNotes 一.简介 pandas提供了很多方 ...

随机推荐

  1. Oracle DG 三种模式(转)

    DG有下面三种模式– Maximum protection– Maximum availability– Maximum performance 在Maximum protection下, 可以保证从 ...

  2. #单元测试#以karma+mocha+chai 为测试框架的Vue webpack项目(二)

    学习对vue组件进行单元测试,先参照官网编写组件和测试脚本. 1.简单的组件 组件无依赖,无props 对于无需导入任何依赖,也没有props的,直接编写测试案例即可. /src/testSrc/si ...

  3. May 09th 2017 Week 19th Tuesday

    Everything you see exists together in a delicate balance. 世上所有的生命都在微妙的平衡中生存. A delicate balance? Can ...

  4. python 带BOM头utf-8的响应解码

    接口响应编码格式为带BOM头utf-8.直接获取响应的text出现乱码. '''dinghanhua2018-11requests text与content,指定响应的encoding''' api ...

  5. 模线性方程&&中国剩余定理及拓展

    一.求解模线性方程 由ax=b(mod n) 可知ax = ny + b 就相当于ax + ny = b 由扩展欧几里得算法可知有解条件为gcd(a, n)整除d 可以直接套用扩展欧几里得算法 最终由 ...

  6. pthread使用

    https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Multithreading/CreatingTh ...

  7. HashMap的工作原理-hashcode和equals原理的再次深入

    前言 首先再次强调hashcode (==)和equals的真正含义(我记得以前有人会说,equals是判断对象内容,hashcode是判断是否相等之类): equals:是否同一个对象实例.注意,是 ...

  8. VI编辑器查找替换

    1.Vi下进行查找 VI命令模式下:输入“/要查找的词”回车就会进入查找,你可以按“n”查找下一个,按“N”查找上一个.类似查找命令“?”与“/”的区别是“/”为向下查找,“?”为向上查找. 2.Vi ...

  9. eclipce导出项目发布到tomcat

    1.右击项目-Except 2.在弹出框中输入“WAR file” 3.点击“next” 在Destinatin选择保存路径,即可 4.将保存的文件复制到tomcat下,启动tomcat之后,会自动解 ...

  10. 【洛谷P3811】[模板]乘法逆元

    乘法逆元 题目链接 求逆元的三种方式: 1.扩欧 i*x≡1 (mod p) 可以化为:x*i+y*p=1 exgcd求x即可 inline void exgcd(int a,int b,int &a ...