随机数的使用是很多算法的关键步骤,例如蒙特卡洛法、遗传算法中的轮盘赌法的过程,因此对于任意一种语言,掌握其各类型随机数生成的方法至关重要,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. 【转】vector中对象指针的排序

    原文:http://blog.csdn.net/tanlijun37/article/details/1948493 vector中对象指针的排序,初步想法是1: 把对象指针存到vector,重载bo ...

  2. makefile 编译指定目录

    makefile 编译指定目录 sub1=test1 sub2=test2 subs = sub1 sub2 SUBDIRS =$(foreach i, $(subs), $($(i))) .PHON ...

  3. Android——Activity生命周期

    启动: 触发 onCreate()   onStart()   onResume() Home键: 触发 onPause()    onStop() back键退出: 触发 onPause()   o ...

  4. [19/03/20-星期三] 常用类_Enum(枚举)类

    一.概念(JDK 1.5之后才有的类) 所有的枚举(英语:enumeration) 类型隐性地继承自 java.lang.Enum.枚举实质上还是类,而每个被枚举的成员实质就是一个枚举类型的实例,他们 ...

  5. 【luogu P4568 [JLOI2011]飞行路线】 题解

    题目链接:https://www.luogu.org/problemnew/show/P4568 卡了一晚上,算是分层图最短路的模板.注意卡SPFA,所以我写了个SLF优化. 同时 AC400祭!~ ...

  6. Mvc5 控制器,视图简单说明

    本系列会比Mvc4更详细.Mvc4记录或没记录的东西这里也会提到. 控制器 自动装配: 一般自动装配对于添加的时候比较好用 视图: 控制器返回的视图,其实就是一些静态的HTML.动态性不好,从控制器传 ...

  7. JavaScript:对事件的反应

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...

  8. webpack——概念的引入

    ## 在网页中会引用哪些常见的静态资源?+ JS - .js .jsx .coffee .ts(TypeScript 类 C# 语言)+ CSS - .css .less .sass .scss+ I ...

  9. vue进阶语法及生命周期函数

    1.calss和style绑定 操作元素的 class 列表和内联样式style是数据绑定的一个常见需求,它两都是属性,所以可以通过v-bind来绑定 1.1绑定HTML class 可以给v-bin ...

  10. Java研究

    Strap   箱线图  峰度  随机过程  马尔科夫  超几何分布  贝叶斯公式 随机变量    德摩根   功率谱   残差  吸收壁   平稳随机    chorst 深入JVM OSGI    ...