[英]Get random seed in Rcpp
I need to minimize a function, let's say f(theta)
.我需要最小化一个函数,比如说
f(theta)
。 In f(theta)
, I draw VERY BIG matrices from a given distribution.在
f(theta)
,我从给定的分布中绘制了非常大的矩阵。 So, throughout the optimization process, I have to keep the same matrices.因此,在整个优化过程中,我必须保持相同的矩阵。 However, as the matrices are too big, I cannot save them.
但是,由于矩阵太大,我无法保存它们。 Thus, for every value of
theta
, I decide to find a way to draw the same matrices.因此,对于
theta
每个值,我决定找到一种方法来绘制相同的矩阵。 This can be done if I define a seed, which will be used each time the function is called.这可以通过定义一个种子来完成,每次调用函数时都会使用它。 But I do not want the user to set the seed, I need the software to get the current seed and then use that seed for every new value of
theta
.但我不希望用户设置种子,我需要软件来获取当前种子,然后将该种子用于
theta
每个新值。
This a simplify example if I use R.如果我使用 R,这是一个简化的例子。
f <- function(theta, SEED) {
.Random.seed <- SEED
# I simplify the problem, I replace the big matrices by a small vector
return(sum((rnorm(10) - theta)^2))
}
optim(par = 0, fn = f, method = "Brent", lower = -1, upper = 1, SEED = .Random.seed)
.Random.seed
allows me to get a seed which will be used in f
. .Random.seed
允许我获得一个将在f
使用的种子。 This ensures that, during the optimization, rnorm(10)
will not be changed although it is not saved.这确保了在优化过程中,
rnorm(10)
不会被更改,尽管它没有被保存。 How can I construct a similar function using Rcpp
?如何使用
Rcpp
构造类似的函数?
Rcpp already deal with this for you, and that is (amply) documented. Rcpp 已经为您处理了这个问题,并且(充分)记录在案。 To wit:
以机智:
> set.seed(42)
> rnorm(3)
[1] 1.370958 -0.564698 0.363128
> rnorm(3)
[1] 0.632863 0.404268 -0.106125
> Rcpp::cppFunction("Rcpp::NumericVector myrn(int n) {return Rcpp::rnorm(3);}")
> myrn(3) # __not reseeded, different__
[1] 1.511522 -0.094659 2.018424
> set.seed(42)
> myrn(3) # reseeded, same as above from R
[1] 1.370958 -0.564698 0.363128
> myrn(3) # ditto
[1] 0.632863 0.404268 -0.106125
>
After you call the function you are supposed to call, set.seed()
, you get identical draws in both R and C++.在你调用你应该调用的函数
set.seed()
,你在 R 和 C++ 中得到相同的绘制。 So call a seed before calling your function and all is well.所以在调用你的函数之前调用一个种子,一切都很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.