欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

VS2019 MPI计算PI

程序员文章站 2022-07-15 16:41:05
...
//#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;
}

相关标签: mpi VS2019