我正在尝试使用蒙特卡洛方法来近似家庭作业的圆周率,通过随机抽样一个单位盒中的点,并计算落入该盒所包围的单位圆内的比率。请参见下面的内容。我被要求使用多线程并行完成这项工作,但我决定在并行化之前先让事情正常工作。因此,我的老师明确要求我使用rand
_
r()表示线程安全。我知道存在更好的伪随机数生成器。然而,我似乎做不到正确的事情,我想我是在播种兰特。
_
r()错误的方式。我尝试使用计算机时间作为种子,但是我得到的值是错误的(大约2.8)。如果我将一些随机数和种子rand()与srand()一起使用,我就能够非常容易地近似π。有人能告诉我这里我错过了什么吗?我写的代码看起来像这样:
#include
#include
#include
#include
double randomNumber( unsigned int seed){
/*_Thread_local*/
double maxRand = (double)RAND_MAX; // Maximum random number, cast to double
double randNum = (double)rand_r( &seed ); // Generate pseudo-random number from seed, cast to double
return 2 * randNum/maxRand - 1; // Recast number between -1 and 1
}
int main( void ){
unsigned int seed = time(NULL);
int numOfPts = (int)1e8 ;
int ptsInCircle = 0 ;
double unitCircleRadius = 1.0 ;
double xpos = 0;
double ypos = 0;
for ( int iteration = 0; iteration < numOfPts; iteration++ ){
xpos = randomNumber(seed);
ypos = randomNumber(seed);
if ( sqrt( pow(xpos, 2) + pow(ypos, 2) ) <= unitCircleRadius ){
ptsInCircle++;
}
}
double myPiApprox = 4.0*((double)ptsInCircle)/((double)numOfPts);
printf("My approximation of pi = %g\n", myPiApprox);
return 0;
}
发布于 2021-03-02 04:28:13
你没有更新
每次都通过循环。
更新局部变量
在
函数,但这不会影响
..。其结果是,每次调用它时都会生成相同的随机数。
您需要将一个指针传递给
的变量设置为
..。
double randomNumber( unsigned int *seed){
/*_Thread_local*/
double maxRand = (double)RAND_MAX; // Maximum random number, cast to double
double randNum = (double)rand_r(seed); // Generate pseudo-random number from seed, cast to double
return 2 * randNum/maxRand - 1; // Recast number between -1 and 1
}
int main( void ){
unsigned int seed = time(NULL);
int numOfPts = (int)1e8 ;
int ptsInCircle = 0 ;
double unitCircleRadius = 1.0 ;
double xpos = 0;
double ypos = 0;
for ( int iteration = 0; iteration < numOfPts; iteration++ ){
xpos = randomNumber(&seed);
ypos = randomNumber(&seed);
if ( sqrt( pow(xpos, 2) + pow(ypos, 2) ) <= unitCircleRadius ){
ptsInCircle++;
}
}
double myPiApprox = 4.0*((double)ptsInCircle)/((double)numOfPts);
printf("My approximation of pi = %g\n", myPiApprox);
return 0;
}
发布于 2021-03-02 04:26:06
你是:
在每次迭代中重新播种随机数生成器,而不是让它做它自己的事情,并且
不仅要在每次迭代中重新播种,还要使用相同的种子
和
,所以您只在对角线上创建元素(其中
)
编辑:在您使用的原始问题中
,这将在对角线上生成排序随机数,在您的编辑中将其更改为
,它始终是完全相同的值。
更改的定义
double randomNumber(unsigned int* seedp) {
// ...
double randNum = (double)rand_r(seedp);
// ...
}
和你的循环:
for ( int iteration = 0; iteration < numOfPts; iteration++ )
xpos = randomNumber(&seed);
ypos = randomNumber(&seed);
// ...
}
https://stackoverflow.com/questions/66429118
复制相似问题