使用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);
尽管在给定 10,000 次迭代的情况下,这并没有产生正确的 pi 值。如果把所有OpenMP的东西都去掉,就可以正常工作了。我应该提到我使用了这里的蒙特卡洛代码: http://www .dartmouth.edu/~rc/classes/soft_dev/C_simple_ex.html
我只是用它来尝试学习 OpenMP。你知道为什么它会集中在 1.4ish 上吗?我不能在多个线程中增加变量吗?我猜问题出在变量 count
上。
谢谢!
I'm trying to learn how to use OpenMP by parallelizing a monte carlo code that calculates the value of PI with a given number of iterations. The meat of the code is this:
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);
Though this is not yielding the proper value for pi given 10,000 iterations. If all the OpenMP stuff is taken out, it works fine. I should mention that I used the monte carlo code from here: http://www.dartmouth.edu/~rc/classes/soft_dev/C_simple_ex.html
I'm just using it to try to learn OpenMP. Any ideas why it's converging on 1.4ish? Can I not increment a variable with multiple threads? I'm guessing the problem is with the variable count
.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我找到了答案。我需要使用 REDUCTION 子句。所以我必须修改的是
:
现在它在 3.14 收敛...耶
Okay, I found the answer. I needed to use the REDUCTION clause. So all I had to modify was:
to:
Now it's converging at 3.14...yay