R语言|生成随机数

Python033

R语言|生成随机数,第1张

首先,如果想要别人复现出跟你一样的结果,要先设置随机种子

Set the seed of R‘s random number generator, which is useful for creating simulations or random objects that can be reproduced.

If you want to generate a decimal number where any value (including fractional values) between the stated minimum and maximum is equally likely, use the runif function.

The first argument is a vector of valid numbers to generate (here, the numbers 1 to 10), and the second argument indicates one number should be returned.

If we want to generate more than one random number, we have to add an additional argument to indicate that repeats are allowed:

一般地,如果你已知一个连续随机变量X的cdf F_X(x)(=P(X<=x))的话,那么F^(-1)(U)(F^(-1)为F的反函数)就符合这个分布(U为(0,1)上的均匀分布),反之亦然。证明很简单,就是直接套定义。

所以你可以写出来F^(-1)这个函数(比如说自定义函数名为FInverse),然后生成随机数组:

randomSequence<-FInverse(runif(n))

对于指数分布来说,

FInverse<-function(p,lambda=1){

-log(1-p)/lambda

}

离散随机变量类似吧。。。

当然,前提是你能写出来F^(-1)。。。(所以我老师说这个方法没啥用。。。)有的分布不好写F^(-1),但是有一些比较巧妙的办法(比如正态分布),这种应该就只能具体问题具体分析了。

先选取一个随机数发生器。

随机数组合的方法:选取一个随机数发生器,生成1000个随机数,令这100个随机数生成数组并命名为t。同时令n=1,命名最终需要的随机数数组为x,选取第二个发生器,生成一个随机数j,且满足1而随机数组合的难点在于,步骤2步骤3的时候随机数种子的选取比较难。这里用的是第一个随机数发生器生成的随机数作为种子,也自己定义其他的种子。