(數據科學學習手札03)Python與R在隨機數生成上的異同

隨機數的使用是很多算法的關鍵步驟,例如蒙特卡洛法、遺傳算法中的輪盤賭法的過程,因此對于任意一種語言,掌握其各類型隨機數生成的方法至關重要,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

?

轉載于:https://www.cnblogs.com/feffery/p/8536955.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/453303.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/453303.shtml
英文地址,請注明出處:http://en.pswp.cn/news/453303.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

音視頻編解碼知識學習詳解(分多部分進行詳細分析)

1. 常用的基本知識 基本概念 編解碼 編解碼器&#xff08;codec&#xff09;指的是一個能夠對一個信號或者一個數據流進行變換的設備或者程序。這里指的變換既包括將信號或者數據流進行編碼&#xff08;通常是為了傳輸、存儲或者加密&#xff09;或者提取得到一個編碼流的操作…

二叉樹非遞歸后序遍歷算法

與正常的非遞歸中序遍歷算法不同于兩點&#xff1a; 一 比正常的中序遍歷算法多了對數據元素的標記。 在壓數據元素入棧&#xff08;標記記為0&#xff0c;用來表示訪問了其左子樹&#xff09;時標記&#xff0c; 還有訪問完左子樹利用gettop&#xff08;&#xff09;獲取雙親…

SQL*Plus命令

SQL*Plus命令 前言 一&#xff1a;SQL*Plus 與數據庫的交互 二&#xff1a;設置SQL* Plus的運行環境 二 - 1 &#xff1a;SET命令概述 二 - 2 &#xff1a;使用SET命令設置運行環境 二 - 2 ____1&#xff1a;Pagesize 變量 1 SYSorcl> show pagesize2 pages…

redis-day1

1 Redis 概述 REmote DIctionary Server(Redis)是一個基于key-value鍵值對的持久化數據庫存儲系統。redis和大名鼎鼎的Memcached緩存服務軟件很像&#xff0c;但是Redis支持的數據存儲類型比Memcached更豐富&#xff0c;包括strings&#xff08;字符串&#xff09;、lists&…

C語言數碼管是共陰共陽程序,C語言實現共陰極數碼管操作

共陰極或者共陽極數碼管&#xff0c;因為其需要電流大&#xff0c;而一般51輸出電流低&#xff0c;需要鎖存器。買的開發板使用的共陰極數碼管。至于其構造&#xff0c;找個相關方面的書看看&#xff0c;這里主要是對做好的電路板進行編程。剛開始的時候&#xff0c;感覺在數碼…

數據庫主要特點

(1)實現數據共享。數據共享包含所有用戶可同時存取數據庫中的數據&#xff0c;也包括用戶可以用各種方式通過接口使用數據庫&#xff0c;并提供數據共享。 (2)減少數據的冗余度。同文件系統相比&#xff0c;由于數據庫實現了數據共享&#xff0c;從而避免了用戶各自建立應用文…

百度與華為全面戰略合作 人工智能手機真的要來了

視頻加載中...12月21日百度和華為在北京宣布達成全面戰略合作。這次合作內容主要包括三點&#xff0c;首先是在語音、語義、視覺和VR上的自然交互&#xff0c;這是百度為華為手機AI賦能的基礎層。第二是基于華為HiAI平臺和百度PaddlePaddle深度學習框架&#xff0c;共建人工智能…

JavaScript數據類型

一、JavaScript數據類型主要分為原始類型和引用數據類型。 原始類型包括(不可拆分的東西)&#xff1a;Number、String、Boolean、Null、Undefined。引用數據類型包括&#xff1a;Object&#xff08;Array&#xff0c;Date&#xff0c;RegExp&#xff0c;Function&#xff09;ty…

funcode拼圖游戲c語言程序,同求funcode平臺下拼圖游戲的C語言代碼

做了好幾天&#xff0c;寫了好多回就是不對&#xff0c;徹底崩潰。。#include "CommonAPI.h"//#include "LessonX.h"#include#define BLOCK_COUNT 4int g_iGameState;intg_iBlockState[BLOCK_COUNT][BLOCK_COUNT];charg_szBlockName[BLOCK_COUNT*BLOCK_COU…

什么是透明傳輸

透明傳輸是指不管所傳數據是什么樣的比特組合&#xff0c;都應當能夠在鏈路上傳送。當所傳數據中的比特組合恰巧與某一個控制信息完全一樣時&#xff0c;就必須采取適當的措施&#xff0c;使收方不會將這樣的數據誤認為是某種控制信息。這樣才能保證數據鏈路層的傳輸是透明的。…

Android 秒級編譯FreeLine

項目地址&#xff1a;FreeLine FreeLine官網: FreeLine 1. 安裝FreeLine插件 File->Settings->Plugins, 搜索輸入FreeLine Plugin, 查找到后進行安裝并重啟Android Studio。 圖1.png安裝好之后&#xff0c;在工具欄就會出一個圖標 圖2.png2. 配置gradle 根目錄build.gr…

JS實現大整數乘法(性能優化、正負整數)

本方法的思路為&#xff1a; 一&#xff1a;檢查了輸入的合法性&#xff08;非空&#xff0c;無非法字符&#xff09; 二&#xff1a;檢查輸入是否可以進行簡單計算&#xff08;一個數為 0&#xff0c;1&#xff0c;1&#xff0c;-1&#xff09; 三&#xff1a;去掉輸入最前面可…

c語言中- gt he,C語言中deta,fabs,lt;stdlib.hgt;,lt;stdio.hgt;分別是什么意思

fabs 編輯本段C語言數學函數:fabs 函數簡介  原型&#xff1a;在TC中原型是extern float fabs(float x);&#xff0c;在VC6.0中原型是double fabs( double x );。   用法&#xff1a;#include   功能&#xff1a;求浮點數x的絕對值   說明&#xff1a;計算|x|, 當x不為…

物理層

目的&#xff1a; 物理層要盡可能地屏蔽掉物理設備和傳輸媒體&#xff0c;通信手段的不同&#xff0c;使數據鏈路層感覺不到這些差異&#xff0c;只考慮完成本層的協議和服務。 給其服務用戶&#xff08;數據鏈路層&#xff09;在一條物理的傳輸媒體上傳送和接收比特流…

C語言中的二級指針(雙指針)

二級指針又叫雙指針。C語言中不存在引用&#xff0c;所以當你試圖改變一個指針的值的時候必須使用二級指針。C中可以使用引用類型來實現。 下面講解C中的二級指針的使用方法。 例如我們使用指針來交換兩個整型變量的值。 錯誤代碼如下&#xff1a; 一級指針 [cpp] view pla…

測試環境服務器硬盤塞滿問題排查

項目中出現的問題 某天下午測試環境服務器出現tab無法補全命令&#xff0c;給出的提示大概意思就是說,無可用空間無法創建臨時文件&#xff0c;不過這次跟上次出現的問題比較像&#xff0c;上次服務器出現的問題&#xff0c;因此樓主判斷可能是服務器數據盤被占滿&#xff0c;果…

alpine_glibc 構建sun jdk 8的docker鏡像

2019獨角獸企業重金招聘Python工程師標準>>> 構建系統基礎鏡像 alpine glibc 的Dockerfile內容如下&#xff1a; alpine:3.6 MAINTAINER tongqiang<tongqiangyingmail.com># Here we install GNU libc (aka glibc) and set C.UTF-8 locale as default.ENV ALP…

單工 半雙工 全雙工

1 單工 單工就是指A只能發信號&#xff0c;而B只能接收信號&#xff0c;通信是單向的&#xff0c;就象燈塔之于航船——燈塔發出光信號而航船只能接收信號以確保自己行駛在正確的航線上。 2 半雙工 半雙工就是指A能發信號給B&#xff0c;B也能發信號給A&#xff0c;但這兩…

c語言兩個循環的ys,c語言編程:從鍵盤輸入兩個數,求它們的最小公倍數

滿意答案flywisdom2019.06.20采納率&#xff1a;44% 等級&#xff1a;9已幫助&#xff1a;1064人main(){int p,r,n,m,temp;printf("Please enter 2 numbers n,m:");scanf("%d,%d",&n,&m);//輸入兩個正整數.if(n{tempn;nm;mtemp;}pn*m;//P是原來…

每日微軟面試題

每日微軟面試題——day 1 <以下微軟面試題全來自網絡> <以下答案與分析純屬個人觀點&#xff0c;不足之處&#xff0c;還望不吝指出^_^> 題&#xff1a;.編寫反轉字符串的程序&#xff0c;要求優化速度、優化空間。 分析&#xff1a;構建兩個迭代器p 和 q &…