蒙特卡洛法多线程求圆周率
来源:互联网 发布:淘宝售假扣48分重开店 编辑:程序博客网 时间:2024/05/21 17:54
#include<iostream>#include<string>#include<pthread.h>#include<cmath>#include<cstdlib>#include<iomanip>#include<cstdio>#include<sys/time.h>#define MAX 100000000using namespace std;double result = 0;int thread_num;int Every_P;pthread_mutex_t mut;void *t_hread(void *arg){ int m = *(int*)arg; if(m != thread_num - 1){ 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; } pthread_mutex_lock(&mut); result = result + (double)count/MAX; pthread_mutex_unlock(&mut);} } if(m == thread_num - 1){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; } pthread_mutex_lock(&mut); result = result + (double)count/MAX; pthread_mutex_unlock(&mut);} } }int main(int argc,char *argv[]){ thread_num = atoi(argv[1]); pthread_t thread[thread_num]; Every_P = MAX/thread_num; pthread_mutex_init(&mut,NULL); int id[thread_num]; struct timeval begin,end; gettimeofday(&begin,NULL); for(int i = 0;i < thread_num;i++){id[i] = i; int err = pthread_create(&thread[i],NULL,t_hread,(void*)&id[i]); } for(int i = 0;i < thread_num;i++){pthread_join(thread[i],NULL); } 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;}
0 0
- 蒙特卡洛法多线程求圆周率
- 求圆周率
- 求圆周率
- 求 圆周率
- 求圆周率
- C#模拟求圆周率
- demo06--求圆周率
- 用乘法求圆周率
- curand库函数求圆周率
- 蒙特卡罗方法求圆周率
- 求圆周率的近似值
- 第二周求圆周率
- C++随机数求圆周率
- C语言实现求圆周率
- 利用蒙特卡洛算法求圆周率
- C++利用技术求圆周率
- 求圆周率的各种方法
- 蒙特卡洛--抛洒点求圆周率
- Lens Distortion Correction
- 树边,前向边,后向边,横叉边
- VTK里面imgedata体绘制遇到的问题
- opkg软件源设
- maven的war依赖
- 蒙特卡洛法多线程求圆周率
- 用arm-none-linux-gnueabi交叉编译Linux内核
- Mybatis MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注入到Spring
- 点击UIViewController任意位置,收起键盘的3种方法
- Spark Streaming资源动态申请和动态控制消费速率原理剖析
- pandas数据分析入门二
- 尾部的零
- AsyncTask异步交互的用法简介
- Android 屏幕(View)坐标系统