# 蒙特卡洛法多线程求圆周率

#include<iostream>
#include<string>
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<cstdio>
#include<sys/time.h>
#define MAX 100000000
using namespace std;
double result = 0;
int Every_P;
int m = *(int*)arg;
for(int i = m * Every_P;i < (m + 1) * Every_P;i++){
double x = sqrt(MAX) * sqrt(MAX - ((i + 0.5)/MAX)*(i + 0.5));
int xx = x;
double count;
if((x - xx) > 0.5){
count = xx + 1;
}
else{
count = xx;
}
result = result + (double)count/MAX;
}
}
for(int i = m * Every_P;i < MAX;i++){
double x = sqrt(MAX) * sqrt(MAX - ((i + 0.5)/MAX)*(i + 0.5));
int xx = x;
double count;
if((x - xx) > 0.5){
count = xx + 1;
}
else{
count = xx;
}
result = result + (double)count/MAX;
}
}
}
int main(int argc,char *argv[]){
struct timeval begin,end;
gettimeofday(&begin,NULL);
for(int i = 0;i < thread_num;i++){
id[i] = i;
}
for(int i = 0;i < thread_num;i++){
}
gettimeofday(&end,NULL);
double pi = result/MAX * 4;
cout<<"pi is:"<<fixed<<setprecision(15)<<pi<<endl;
int time = (end.tv_sec - begin.tv_sec) * 1000000 + (end.tv_usec - begin.tv_usec);
printf("time: %d us\n", time);
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：蒙特卡洛法多线程求圆周率 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)