VS2019 MPI计算PI

//#include "mpi.h"
//#include<iostream>
//using namespace std;
//int main(int argc,char *argv[]) 
//{	
//
//	int myid, numprocs, namelen;
//	char process_name[MPI_MAX_PROCESSOR_NAME];
//	MPI_Init(&argc,&argv);
//	MPI_Comm_rank(MPI_COMM_WORLD,&myid);
//	MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
//	MPI_Get_processor_name(process_name,&namelen);
//	if(myid==0)
//	{
//		cout << "number of processes: " << numprocs << endl;
//	}
//	cout << process_name<< ": Hello world from process "<<myid << endl;
//
//	MPI_Finalize();
//	return 0;
//
//
//
//
//}
//ctrl+k+U 取消注释
//ctrl+k+C 添加注释
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "mpi.h"

int main(int argc,char* argv[])
{
	long npoints ;
	double circle_count = 0; 
	double sum_c = 0;
	int myid, numprocs, name_length;
	char procs_name[MPI_MAX_PROCESSOR_NAME];
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
	MPI_Comm_rank(MPI_COMM_WORLD,&myid);
	MPI_Get_processor_name(procs_name, &name_length);
	MPI_Status status;
	int i,j;
	srand((int)time(0));
	double x, y, pi, sum = 0.0, PII = 3.1415926535897932384643;
	if(myid==0)
	{
		npoints = 1000000;
		for (j = 1; j < numprocs; j++) {
			MPI_Send(&npoints, 1, MPI_LONG, j, 0, MPI_COMM_WORLD);
//			printf("0Send->%d\n", j);
		}
	}
	else {
		MPI_Recv(&npoints, 1, MPI_LONG, 0, 0, MPI_COMM_WORLD, &status);
//		printf("0Recv->%d\n", myid);
	}

	for(i=myid;i<npoints;i+=numprocs)
	{	//rand() return[0,RAND_MAX]->rand() / (RAND_MAX + 1) [0,1) ->rand() / (RAND_MAX ) [0,1]
		x = rand() / (RAND_MAX +0.0);
		y = rand() / (RAND_MAX +0.0);
		if((x-1)*(x-1)+(y-1)*(y-1)<=1)
		{
			circle_count = circle_count + 1;
		}
	}
	MPI_Reduce(&circle_count,&sum_c,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
	if (myid == 0) {
		pi = 4.0 * sum_c / npoints;
		printf("%lf\n", pi);
		printf("%lf", pi - PII);
	}

	MPI_Finalize();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值