【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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥宅_Sean

公众号“肥宅Sean”欢迎关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值