使用OpenMP计算圆周率值 [英] Using OpenMP to calculate the value of PI
问题描述
我想学习如何通过并行蒙特卡罗code,计算PI与迭代给定数量的值使用OpenMP的。在code的肉是这样的:
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);
尽管这不是产生对给定的10,000次重复圆周率的适当值。如果所有的OpenMP的东西取出来,它工作正常。我要指出,我用蒙特卡罗code从这里: HTTP: //www.dartmouth.edu/~rc/classes/soft_dev/C_simple_ex.html
我只是用它来尝试学习OpenMP的。任何想法,为什么它的收敛于1.4ish?我不能增加多线程的变量?我猜问题是与变量计数
。
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
.
谢谢!
推荐答案
好吧,我找到了答案。我需要使用的减少子句。因此,所有我不得不修改为:
Okay, I found the answer. I needed to use the REDUCTION clause. So all I had to modify was:
#pragma omp parallel shared(chunk,count) private(i)
到
#pragma omp parallel shared(chunk) private(i,x,y,z) reduction(+:count)
现在它汇聚在3.14 ...耶
Now it's converging at 3.14...yay
这篇关于使用OpenMP计算圆周率值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!