日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【MPI高性能计算】蒙特卡洛方法计算pi值

發布時間:2025/4/16 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【MPI高性能计算】蒙特卡洛方法计算pi值 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

蒙特卡洛方法

就是通過概率模擬來近似計算。
其實算法進度不是很高。

代碼

在下面代碼中的input文件中的內容是

10000000

運行效果:下面用四個核來做計算

PS D:\C++\VS\repo\MPI-DEMO\Debug> mpiexec -n 4 ./MPI-DEMO.exe 3.14111 #include<stdio.h> #include<string.h> #include<mpi.h> #pragma warning(disable : 4996) #define MAX_STRING 100 using namespace std; #include <fstream> #include <ctime> #include <iostream>#define random() (rand() / double (RAND_MAX) * 2 - 1)int main(void) {int comm_sz;int my_rank;MPI_Init(NULL, NULL);MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);// 只有一個線程的時候不操作if (comm_sz <= 1) {MPI_Finalize();return 0;}long long int count_time; // 總的計算次數long long int Cal[2] = { 0 };if (my_rank == 0) {ifstream cin("D:\\C++\\VS\\repo\\MPI-DEMO\\MPI-DEMO\\input.txt");cin >> count_time;long long int tempCal[2] = { 0 };long long int width = count_time / (comm_sz - 1);long long int reminder = count_time % (comm_sz - 1);long long int temp_count_time;for (int i = 1; i < comm_sz; ++i){temp_count_time = width;if (i <= reminder) temp_count_time++;MPI_Send(&temp_count_time, 1, MPI_LONG_LONG_INT, i, 0, MPI_COMM_WORLD);}for (int i = 1; i < comm_sz; ++i){MPI_Recv(tempCal, 2, MPI_LONG_LONG_INT, i, 0, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);for (int j = 0; j < 2; ++j) { Cal[j] += tempCal[j]; }}std::cout << 4.0 * Cal[0] / count_time << endl;} // 運算的子節點else {srand((unsigned)time(NULL));MPI_Recv(&count_time, 1, MPI_LONG_LONG_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);Cal[1] = count_time;Cal[0] = 0;double x, y, dst;for (int i = 0; i < count_time; ++i) {x = random();y = random();dst = x * x + y * y;if (dst <= 1) Cal[0] += 1;}MPI_Send(Cal, 2, MPI_LONG_LONG_INT, 0, 0, MPI_COMM_WORLD);}MPI_Finalize();return 0; }

總結

以上是生活随笔為你收集整理的【MPI高性能计算】蒙特卡洛方法计算pi值的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。