Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <mpi.h>
- /*
- # Goal
- Estimate pi using Leibniz formula:
- pi/4 = \sum_{n=0}^{\infty} \frac{(-1)^{n}}{sn + 1}.
- Example from:
- Pitt-Francis and Whiteley, Guide to Scientific Computing in C++, Springer 2012, ch.11
- # Compilation
- $ mpic++ -o leibniz.out leibniz.cpp
- # Execution, and expected (approximate) result.
- Result of my laptop below.
- Since this machine has four processors, there is no gain increasing
- the number of proccesses to five or more.
- Speedup = T_1 / T_p = [1, 1.846, 2.599, 3.313]
- Efficiency = Speedup / p = [1, 0.923, 0.866, 0.828]
- $ time mpirun -np 1 ./leibniz.out
- pi is approximated as 3.141592653!
- real 0m14.397s
- user 0m14.222s
- sys 0m0.048s
- $ time mpirun -np 2 ./leibniz.out
- pi is approximated as 3.141592653!
- real 0m7.801s
- user 0m15.170s
- sys 0m0.073s
- $ time mpirun -np 3 ./leibniz.out
- pi is approximated as 3.141592653!
- real 0m5.539s
- user 0m15.671s
- sys 0m0.105s
- $ time mpirun -np 4 ./leibniz.out
- pi is approximated as 3.141592653!
- real 0m4.346s
- user 0m15.925s
- sys 0m0.174s
- $ time mpirun -np 8 ./leibniz.out
- pi is approximated as 3.141592653!
- real 0m4.411s
- user 0m16.172s
- sys 0m0.280s
- */
- int main(int argc, char* argv[]) {
- long long max_n = 1000000000;
- MPI::Init(argc, argv);
- int num_procs = MPI::COMM_WORLD.Get_size();
- int rank = MPI::COMM_WORLD.Get_rank();
- double sum = 0;
- for (long long n=rank; n<max_n; n+=num_procs) {
- double tmp = 1.0 / ( 2.0 * (double)n + 1);
- if (n % 2 == 0) {
- sum += tmp;
- } else {
- sum -= tmp;
- }
- }
- double global_sum;
- MPI::COMM_WORLD.Reduce(&sum, &global_sum, 1, MPI::DOUBLE, MPI::SUM, 0);
- // 1 : count, 0: destination
- if (rank == 0) {
- std::cout << std::setprecision(10) <<
- "pi is approximated as " << 4.0*global_sum << "!\n";
- }
- MPI::Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement