我正在编写一个使用Rcpp软件包的R软件包。到目前为止,我一直在R版本4.0.0的macOS Catalina上进行工作和测试。使用R中的set.seed
,可以从Mac中获得可重复的结果。但是,在Windows 10机器(也使用R 4.0.0)上进行测试时,我得到了不同的结果(使用相同的种子)。
在程序包中,我调用std::random_shuffle
生成排列。我正在使用the Rcpp website中的代码来执行此操作。在C ++中,它是:
#include<Rcpp.h>
inline int randWrapper(const int n) { return floor(unif_rand()*n); }
// [[Rcpp::export]]
Rcpp::NumericVector randomShuffle(Rcpp::NumericVector a) {
// clone a into b to leave a alone
Rcpp::NumericVector b = Rcpp::clone(a);
std::random_shuffle(b.begin(), b.end(), randWrapper);
return b;
}
然后可以从R获取并称为
a <- 1:8
set.seed(42)
randomShuffle(a)
运行此代码,我在Mac上获得8 1 4 2 7 5 3 6
,在Windows上获得1 4 3 7 5 8 6 2
。
起初,我认为这可能是由于在两个操作系统上实现unif_rand()
的方式不同,但是在我测试时
#include<Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector rint() {
Rcpp::NumericVector a(1);
a[0] = unif_rand();
return a;
}
我在两台计算机上都得到0.914806
相同的结果。如果将unif_rand()
替换为R::runif(0,1)
,也会发生相同的情况。我认为Mac的g++
和clang++
结果相同。
任何有关解决此问题的建议或见解(如果可能)将不胜感激!
I 思考您感到困惑,因为std::random_shuffle()
实际上是标准的C ++库函数,并且其RNG与R不相关。我想,由于使用不同的C ++库,因此在macOS和Windows上获得不同的结果。
然后您获得runif()
或unif_rand()
值的结果证实了这一思路。只是std::random_shuffle()
不使用这些值。
因此,正如@BenBolker所暗示的那样,对于跨操作系统的[[可再现结果,您可能希望坚持使用R(和Rcpp)功能。