R中将多个变量赋予另外多个变量——一个脑残的方案

探索R中随机数(零)

Dante posted @ 2014年4月02日 01:50 in R语言 with tags 随机数 R runif , 1614 阅读

下午师妹问我,如果在R中一次生成多个随机数,和在一个循环中生成的随机数,会有什么不同?

简单地做个实验:

set.seed(123)
runif(3)
set.seed(123)
for(i in 1:3) {
    print(runif(1))
}

两个输出的结果是一样的。无论是一次生成多个随机数,还是在一个循环中生成随机数,都是从一个种子出发,生成一个随机序列。如果初始的种子一样,那么生成的随机序列也是一样的。

从这里出发,开始探索一下R中随机数生成的原理。于是去看R中的源代码,在R 中直接输入runif得到的结果是:

> runif
function (n, min = 0, max = 1) 
.External(C_runif, n, min, max)
<bytecode: 0x9bd23a4>
<environment: namespace:stats>

.External调用C_runif,而C_runif其实是一个指向动态链接库的指针,并不是一个函数的名字(看C_runif没有带有引号可知,关于这一点可以参考stackoverflow上的一个讨论 )。在R的源代码下,可以在src/main/name.c中,找到对应runif的函数:do_random2,还可以看到do_random2对应了多种分布,通过一个偏移量(offset)来区分,接受三个参数。

于是,我们找到了runif的底层源码,至于这个源代码能告诉我们什么,有空再写。

Avatar_small
AP 10th History Mode 说:
2022年9月17日 03:50 History can guide learners to see trends and processes from a broader, holistic perspective and to understand them. Through History, they come into contact with other cultures and societies and in this way they gain a more holistic understanding of the contemporary world and their place in this broader context. Telugu Medium, AP 10th History Model Paper English Medium & Urdu Medium Students of the State Board can download the AP 10th History Model Paper 2023 Pdf with Answers designed based on the revised syllabus and curriculum of the course. Class teachers and leading institutional experts are designed and suggested the Part-A, Part-B, Part-C, and Part-D exams like SA-1, SA-2, FA-1, FA-2, FA-3, FA-4 along with Assignments.

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter