在cuda中实现随机生成器
implementing random generator in cuda
我想在cuda中将这个函数实现为device/global函数,以获得高斯分布的随机数。
double gasdev2() {
double ran3n(long *seed);
// double genrand64_real3();
static int iset=0;
static double gcos;
double tmp1,tmp2;
if (iset==0) {
tmp1=sqrt(-2*log(ran3n(&seed)));
tmp2=pi2*ran3n(&seed);
// tmp1=sqrt(-2*log(genrand64_real3()));
// tmp2=pi2*genrand64_real3();
gcos=tmp1*cos(tmp2);
iset=1;
return tmp1*sin(tmp2);
//return 1;
}else{
iset=0;
return gcos;
//return 1;
}
}
这些函数调用基本都会用到这个函数,串口代码是这样的
for(int i=0;i<NTO;i++){
Frdx[j]=gasdev2()*ranm[j]*tconst;
Frdy[j]=gasdev2()*ranm[j]*tconst;
Frdz[j]=gasdev2()*ranm[j]*tconst;
}
我建议不要自己实现,而是使用 Thrust:
提供的随机算法
uint32_t seed = 1234;
thrust::default_random_engine rng(seed);
thrust::uniform_real_distribution<float> dist(0.0f, 1.0f);
float random_value_1 = dist(rng);
float random_value_2 = dist(rng);
您可以在主机和设备代码中使用它。
看看 Thrust examples.
我想在cuda中将这个函数实现为device/global函数,以获得高斯分布的随机数。
double gasdev2() {
double ran3n(long *seed);
// double genrand64_real3();
static int iset=0;
static double gcos;
double tmp1,tmp2;
if (iset==0) {
tmp1=sqrt(-2*log(ran3n(&seed)));
tmp2=pi2*ran3n(&seed);
// tmp1=sqrt(-2*log(genrand64_real3()));
// tmp2=pi2*genrand64_real3();
gcos=tmp1*cos(tmp2);
iset=1;
return tmp1*sin(tmp2);
//return 1;
}else{
iset=0;
return gcos;
//return 1;
}
}
这些函数调用基本都会用到这个函数,串口代码是这样的
for(int i=0;i<NTO;i++){
Frdx[j]=gasdev2()*ranm[j]*tconst;
Frdy[j]=gasdev2()*ranm[j]*tconst;
Frdz[j]=gasdev2()*ranm[j]*tconst;
}
我建议不要自己实现,而是使用 Thrust:
提供的随机算法 uint32_t seed = 1234;
thrust::default_random_engine rng(seed);
thrust::uniform_real_distribution<float> dist(0.0f, 1.0f);
float random_value_1 = dist(rng);
float random_value_2 = dist(rng);
您可以在主机和设备代码中使用它。 看看 Thrust examples.