使用 .C() : random value is the same every time 从 R 调用 C 代码

标签 c r

我有与提问者相反的问题:Passing seed/Setting seed/ C within R code .我的问题是我想使用 R 随机数生成器在 C 代码中生成一个随机数,但每次运行它时,我都会得到相同的“随机”值。这是我的代码(包括我碰巧使用的头文件,这些头文件并不是代码片段所必需的):

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <math.h>   // C header files

#include <R.h>
#include <R_ext/Utils.h>
#include <Rmath.h>

void main(){
GetRNGstate();
double u = unif_rand();
PutRNGstate();
Rprintf("%f\n",u);
}

现在我在使用 R CMD SHLIB 编译并使用 dyn.load() 后从 R Windows GUI 调用它:

> .C("main")
0.000889
list()

现在,如果我关闭 R,重新启动,然后再次 dyn.load()(但不进行第二次编译):

> .C("main")
0.000889
list()

根据我在互联网上找到的各种代码和“Writing R Extensions”手册,这不应该发生。但我可能只是错过了一步?

最佳答案

我无法复制这个。

这是一个完整且可重现的示例,仅依赖于 inline帮助构建、编译、链接和加载最小函数的包:

R> library(inline)
R> src <- '
+   GetRNGstate();
+   double u = unif_rand();
+   Rprintf("%f\\n",u);
+   PutRNGstate();
+   return R_NilValue;
+ '
R> fun <- cxxfunction(signature(), body=src)
R> set.seed(42)
R> invisible(fun())   # invisible to suppress the NULL return in foo()
0.914806
R> invisible(fun())
0.937075
R> invisible(fun())
0.286140
R> invisible(fun())
0.830448
R> invisible(fun())
0.641746
R> 

如果我重置种子,相同的序列开始:

R> set.seed(42)
R> invisible(fun())
0.914806
R> invisible(fun())
0.937075
R> invisible(fun())
0.286140
R> 

您可能正在加载/运行与设置 RNG 相关的具有副作用的不同函数。此外,以防万一,您的示例无法加载,因为您无法将带有 main() 的函数加载到 R 本身。

关于使用 .C() : random value is the same every time 从 R 调用 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14555135/

相关文章:

c++ - 将 config.json 文件与 BBC Micro 一起使用 :bit Mbed online compiler

c - 如何使用 Rembedded 解析因子/数据帧

减少 ggplot2 中离散轴刻度之间的空间

c - 这两种说法有什么区别?

C 奇怪的统计 st_mode

c - 查看数字是否小于 2^32

python - 从 bash 脚本中生成并执行 R、Python 等脚本

r - 预测每小时时间序列的模型

c++ - R:dyn.load 错误(文件,DLLpath = DLLpath,...)

R中介分析——引导