我正在研究一套 https://github.com/osorensen/BayesMallows,它使用来自 RcppArmadillo 的随机数。该软件包运行 MCMC 算法,为了获得精确的再现性,用户应该能够设置随机数种子。这样做时,看起来就像arma::randg()
从伽马分布生成随机数的函数在不同平台上返回不同的值。情况并非如此arma::randu()
or arma::randn()
。这是否与以下事实有关:arma::randg()
需要 C++11?
以下是我在运行 R3.5.2 的 macOS 10.13.6 上得到的结果:
library(Rcpp)
library(RcppArmadillo)
sourceCpp(code = '
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
double random_gamma() {
return arma::randg();
}
// [[Rcpp::export]]
double random_uniform() {
return arma::randu();
}
// [[Rcpp::export]]
double random_normal() {
return arma::randn();
}
'
)
replicate(2, {set.seed(1); random_gamma()})
#> [1] 1.507675 1.507675
replicate(2, {set.seed(432); random_gamma()})
#> [1] 0.02234341 0.02234341
replicate(2, {set.seed(1); random_uniform()})
#> [1] 0.2655087 0.2655087
replicate(2, {set.seed(1); random_normal()})
#> [1] -1.390378 -1.390378
Created on 2019-02-22 by the reprex package https://reprex.tidyverse.org (v0.2.1)
以下是我在运行 R3.5.2 的 Windows 10 上得到的结果:
library(Rcpp)
library(RcppArmadillo)
sourceCpp(code = '
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
double random_gamma() {
return arma::randg();
}
// [[Rcpp::export]]
double random_uniform() {
return arma::randu();
}
// [[Rcpp::export]]
double random_normal() {
return arma::randn();
}
'
)
replicate(2, {set.seed(1); random_gamma()})
#> [1] 0.2549381 0.2549381
replicate(2, {set.seed(432); random_gamma()})
#> [1] 0.2648896 0.2648896
replicate(2, {set.seed(1); random_uniform()})
#> [1] 0.2655087 0.2655087
replicate(2, {set.seed(1); random_normal()})
#> [1] -1.390378 -1.390378
Created on 2019-02-22 by the reprex package https://reprex.tidyverse.org (v0.2.1)
可以看出,生成的随机数arma::randg()
内部一致,但平台之间有所不同。
我尝试使用犰狳文档中的说明设置种子:
library(Rcpp)
library(RcppArmadillo)
sourceCpp(code = '
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
double random_gamma(int seed) {
arma::arma_rng::set_seed(seed);
return arma::randg();
}
'
)
replicate(4, random_gamma(1))
#> Warning in random_gamma(1): When called from R, the RNG seed has to be set
#> at the R level via set.seed()
#> [1] 1.3659195 0.6447221 1.1771862 0.9099034
Created on 2019-02-22 by the reprex package https://reprex.tidyverse.org (v0.2.1)
然而,正如警告所示和结果所示,种子不会以这种方式设置。
使用时有没有办法在平台之间获得可重现的结果arma::randg()
,或者我是否需要使用 RcppArmadillo 中提供的其他一些随机数生成器来实现伽玛分布?
Update
正如评论中指出的,使用R::rgamma()
解决了这个问题。以下代码在 Mac 和 Windows 上返回相同的数字:
library(Rcpp)
sourceCpp(code = '
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double random_gamma() {
return R::rgamma(1.0, 1.0);
}
'
)
replicate(2, {set.seed(1); random_gamma()})
#> [1] 0.1551414 0.1551414
Created on 2019-02-22 by the reprex package https://reprex.tidyverse.org (v0.2.1)
这为我解决了。但是,我不确定问题是否已解决,因为这似乎是意外行为,所以将其保留。