Public feed #528896

MPI Pi Estimator

public cpp v1 · immutable
Raw Edit
·published 2007-06-01 18:40 UTC
rendered paste body
/*	Author: Cyle Riggs 			3mail:	cyle !!at!!	riggs family web %d0t% net*/#include <iostream>#include <iomanip>#include <cstdlib>#include <cmath>#include <map>#include <vector>#include "mpi.h"#define TAG_POINTS 11#define TAG_INCIRCLE 12#define REALPI 3.14159265358979323846264338327950288419716939937510using namespace std;struct CPoint {	double x;	double y;};double drand( double low, double high );int main( int argc, char* argv[] ) {	MPI_Status status;	MPI_Init( &argc, &argv );		int size = -1;	int rank = -1;	MPI_Comm_size( MPI_COMM_WORLD, &size );	MPI_Comm_rank( MPI_COMM_WORLD, &rank );		srand( (rank+1) * time(NULL) + clock() );		unsigned long int count = 0;	if( rank == 0 ) {		cout << "This program will make random points and use them to determine pi, the greater the number of points, the better the accuracy" << endl << endl;		cout << "# of points? " << flush;		cin >> count;	}		MPI_Bcast( &count, 1, MPI_INT, 0, MPI_COMM_WORLD );		//If the user chose 0 quit here	if( count == 0 ) {		MPI_Finalize();		return 0;	}		vector<CPoint> results;	map<unsigned long int,unsigned long int> job_map;	for( unsigned long int i = 0; i < count; i++ ) {		job_map[i%size]++;	}		if( rank == 0 ) {		cout << "Generating ~" << job_map[rank] << " random points per process" << endl;	}		vector<CPoint> mypoints;	for( unsigned long int i = 0; i < job_map[rank]; i++ ) {		CPoint p;		p.x = drand( -1.0, 1.0 ); //Generate X for the point		p.y = drand( -1.0, 1.0 ); //Generate Y for the point				mypoints.push_back( p );	}		double my_in_circle = 0.0;		for( vector<CPoint>::iterator point = mypoints.begin(); point != mypoints.end(); point++ ) {		if( (pow(point->x,2)+pow(point->y,2)) < 1 ) {			my_in_circle++;		}	}		double final_in_circle = 0.0;		//Add together everybody's count of points in the circle	MPI_Reduce( &my_in_circle, &final_in_circle, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD );		if( rank == 0 ) {		double est_pi = (4.0 * (final_in_circle/count));		double accuracy = est_pi - REALPI;			//PI is the 4 * (# of points that fell in circle / the total number of points)		cout << endl << endl;		cout << "Pi: " << est_pi << endl;		cout << "Accuracy: " << accuracy << endl;	}		MPI_Finalize();		return 0;}double drand( double low, double high ) {	double retval = static_cast<double>( rand() ) / RAND_MAX;	return low + ((high - low) * retval);}