4
我在学习如何使用OpenMP并行化蒙特卡罗代码,该代码可以计算PI的值,并给定迭代次数。代码的肉是这样的:使用OpenMP来计算PI的值
int chunk = CHUNKSIZE;
count=0;
#pragma omp parallel shared(chunk,count) private(i)
{
#pragma omp for schedule(dynamic,chunk)
for (i=0; i<niter; i++) {
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
}
pi=(double)count/niter*4;
printf("# of trials= %d , estimate of pi is %g \n",niter,pi);
虽然这不产生适当的价值为pi给予10,000次迭代。如果所有的OpenMP东西都被取出,它就可以正常工作。我应该提到,我使用了蒙特卡罗代码:http://www.dartmouth.edu/~rc/classes/soft_dev/C_simple_ex.html
我只是用它来试图学习OpenMP。任何想法为什么它收敛在1.4ish?我可以不使用多个线程递增变量吗?我猜测问题是变量count
。
谢谢!