使用 从 R 调用 C 代码.C():随机值每次都相同

  • 本文关键字:随机 调用 代码 使用
  • 更新时间 :
  • 英文 :


我与这个提问者有相反的问题:在 R 代码中传递种子/设置种子/C。我的问题是我想使用 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("%fn",u);
}

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

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

现在,如果我再次关闭R,重新启动并dyn.load()(但没有第二次编译):

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

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

我无法复制这个。

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

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 本身中。

最新更新