您好我正在使用openMP进行经典“monte carlo pi approximation”问题的简单C ++练习。我的代码是这样的:
int main () {
Ran ran(time( NULL ) );
int N = 2000000; //run the loop for N times
int a[N];
double sum=0;
// for loop execution
#pragma omp for private(a[i]) reduction(+:sum)
for( int i = 0; i < N; i = i + 1 ) {
double xx=ran.doub();
double yy=ran.doub();
double rr=r(xx, yy);
double cc=count(rr);
a[i]=cc;
sum+=a[i];
//cout << "element of a: " << a[i] << endl;
//cout << "x: " << xx << endl;
//cout << "sum: " << sum << endl;
}
cout << "sum: " << sum << endl;
cout << "pi?: " << 4*sum/N << endl;
return sum/N;
}
它运行良好,N = 2000000,有20个核心。但是当我使N更大时,如2.5e6,它开始出现分段错误。