基于相同的种子复制R中SAS(rancor)中生成的随机法线?

时间:2015-06-10 17:41:59

标签: r sas random-sample

给定相同的种子,有没有办法在R中使用rannor函数生成在SAS中生成的完全相同的随机正态数?

3 个答案:

答案 0 :(得分:2)

要进行这些匹配,您需要做两件事:

  • 用于生成随机数的种子
  • 用于生成随机数的公式

SAS用于rannor(我也想到rand,但我还没有看到确认),以下算法(在Psuedo-Random Numbers: Out of Uniform中找到,由Robert Johnson和刘辉):

rannor_result = (−2* log(U1))**.5*cos(2*constant('pi')*U2)

其中U1和U2是统一数字流中的两个数字。 (也可以获得第二个数字,但据我所知,该数字将被丢弃。)

请参阅以下SAS datastep:

data test1;
  U1 = ranuni(7);
  U2 = ranuni(7);
  X1 = (−2* log(U1))**.5*cos(2*constant('pi')*U2);
  U1 = ranuni(7);
  U2 = ranuni(7);
  X2 = (−2* log(U1))**.5*cos(2*constant('pi')*U2);
run;
data test2;
  x1 = rannor(7);
  x2 = rannor(7);
run;

test1test2具有相同的rannorm数值。

我怀疑R和SAS共享普通的PRNG算法,特别是因为rannor使用的算法不是很好(你应该使用rand使用Mersenne Twister更好,更好。但是,只要输出RANUNI结果,您就可以轻松地要求SAS输出它使用的种子。

您可以要求SAS以这种方式执行此操作:

data rands_uni;
  seed=7;
  do _i_=1 to 10;
    seed1 = seed;
    call ranuni(seed,x1);
    seed2=seed;
    call ranuni(seed,x2);
    output;
  end;
run;

然后你可以在R中计算出rannor结果(即从x1和x2)。我把种子包括在那里供参考 - 也许R确实有能力使用它们。上面的论文确实引用了用于ranuni的算法SAS,但是它也指出由于使用了一些修正(或者,由于浮点精度问题?),你无法完美地复制它。

答案 1 :(得分:0)

我测试两者,似乎没有。

data _null_;
CALL STREAMINIT(1245);
do i=1 to 10;
x2 = rand('NORMAL',0,1);
put x2;
end;
run;
/*
-1.295643934
0.0651085355
-0.391011151
1.1024205822
2.0712099724
-0.296163515
0.898941256
-0.584950901
0.2027164546
-0.986522152*/

set.seed(1245)
df<-rnorm(10,0,1)
df
 [1]  0.41914007 -1.45583361 -1.45588008 -1.01564637 -0.53309914 -0.68360608  0.32590880 
 [8]  0.92256137 -0.05085288  0.29722361

答案 2 :(得分:0)

Proc IML;
Call RandSeed(6);
U1 = J(6,1);
U2 = J(6,1);
/* Weibull Distribution */
Call RandGen(U1,"WEIBULL",1.7737152,13.164695);
Print "Weibull Distribution:" U1;
/* Unifrom Distribution */
Call RandGen(U2,"UNIFORM",0,1);
Print "Uniform Distribution:" U2;

Submit/R;
    set.seed(6);
    ## Weibull Distribution;
    U1 <- rweibull(6,1.7737152,13.164695);
    cat("Weibull Distribution:", U1, "\n");
    ## Uniform Distribution;
    U2 <- runif(6,0,1);
    cat("Unifrom Distribution:", U2, "\n");
EndSubmit;

Quit;

enter image description here