我有以下 c 函数致力于实现拒绝采样器。MersenneTwiser.h 生成一个介于 0 和 1 之间的随机数。我遇到的问题是 rnorm 函数。我正在使用 while 循环来拒绝一些样本。现在是废话,因为它还没有完成。在当前形式下,程序返回 0.00000。
#include<stdio.h>
#include<math.h>
#include"MersenneTwister.h"
MTRand rng;
double p;
double prop;
int sign;
double dubexp(double theta){
p = rng.rand();
if ((p-0.5) > 0) sign= 1;
if ((p-0.5) < 0) sign= -1;
prop = -(1/theta)*sign*log(1-2*abs(p-0.5));
return(prop);
}
double u;
double theta;
double t;
double z;
double c;
double x;
double rnorm(double theta, double c){
t=rng.rand();
while (z == t)
{
x=dubexp(theta);
u=rng.rand();
z=x;
}
return z;
}
int main(){
theta=1;
c=1;
u = rnorm(theta,c);
printf("%f",u);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我删除 while 循环,它会返回正确的 z 值。如下:
double rnorm(double theta, double c){
t=rng.rand();
x=dubexp(theta);
u=rng.rand();
z=x;
return z;
}
Run Code Online (Sandbox Code Playgroud)
while 循环从不运行
double rnorm(double theta, double c){
t=rng.rand();
while (z == t) // <-- this condition is never true, so the loop doesn't run and the function just returns z
{
x=dubexp(theta);
u=rng.rand();
z=x;
}
return z;
}
Run Code Online (Sandbox Code Playgroud)
请参阅上面的评论。
此外,z是全局定义的。全局变量和静态变量被初始化为零。这就是原因。