Skip to content

Instantly share code, notes, and snippets.

@omarsamir27
Created January 21, 2023 00:31
Show Gist options
  • Save omarsamir27/3383aa8cd4a1c68cbaf9e2b155f91ab2 to your computer and use it in GitHub Desktop.
Save omarsamir27/3383aa8cd4a1c68cbaf9e2b155f91ab2 to your computer and use it in GitHub Desktop.
Example usage of MPI to calculate the value of pi
#include <iostream>
#include <mpi.h>
#include <iomanip>
/* This program approximates the value of pi using the Leibniz formula.
The Leibniz formula for pi [1] is attributed to Gottfried Wilhelm
Leibniz (1646-1716) . The formula goes as follows:
1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = pi/4
This is an MPI implementation, MPI (Message Passing Interface) is a C API for multiprocessing ,
it works for multicore , multiprocessor and multi-node setups.
MPI has several implementations , 2 of them are OpenMPI and MPICH. They have the same interface but implement internal
details differently.
This implementation is accurate until 3.151592, after that some digits are different from the real value,
this is not an implementation error but a property of the forumla , see [1] for explanation
This is an MPI parallel implementation in C++ , for Python implementations in MPI , serially or CUDA see [3]
* Author : Omar Mohamed <omarmsamir27@gmail.com> <github.com/omarsamir27>
* for HPC Centre in Alexandria Library <https://hpc.bibalex.org> <github.com/hpcalex>
[1] https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80
[2] https://www.mcs.anl.gov/research/projects/mpi/
[3] https://github.com/hpcalex/pi4py
*/
int main(int argc, char *argv[]) {
auto num_terms = 10e7;
MPI::Init(argc, argv);
auto my_rank = MPI::COMM_WORLD.Get_rank();
auto num_procs = MPI::COMM_WORLD.Get_size();
double local_sum=0,term ;
for (int i = num_terms - my_rank; i >= 0 ; i-=num_procs) {
term = 1 / (2.0 * ((double) (i)) + 1.0);
local_sum += i%2==0 ? term : -term ;
}
double pi_approx=0;
MPI::COMM_WORLD.Reduce(&local_sum,&pi_approx,1,MPI::DOUBLE,MPI::SUM,0);
if (my_rank == 0){
pi_approx *= 4;
std::cout << std::setprecision(20) << pi_approx;
}
MPI::Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment