Estimating the value of Pi using Monte Carlo | Parallel Computing Method
Given two integers N and K representing number of trials and number of total threads in parallel processing. The task is to find the estimated value of PI using the Monte Carlo algorithm using the Open Multi-processing (OpenMP) technique of parallelizing sections of the program.
Input: N = 100000, K = 8
Output: Final Estimation of Pi = 3.146600
Input: N = 10, K = 8
Output: Final Estimation of Pi = 3.24
Input: N = 100, K = 8
Output: Final Estimation of Pi = 3.0916
Approach: The above given problem Estimating the value of Pi using Monte Carlo is already been solved using standard algorithm. Here the idea is to use parallel computing using OpenMp to solve the problem. Follow the steps below to solve the problem:
- Initialize 3 variables say x, y, and d to store the X and Y co-ordinates of a random point and the square of the distance of the random point from origin.
- Initialize 2 variables say pCircle and pSquare with values 0 to store the points lying inside circle of radius 0.5 and square of side length 1.
- Now starts the parallel processing with OpenMp together with reduction() of the following section:
- Iterate over the range [0, N] and find x and y in each iteration using srand48() and drand48() then find the square of distance of point (x, y) from origin and then if the distance is less than or equal to 1 then increment pCircle by 1.
- In each iteration of the above step, increment the count of pSquare by 1.
- Finally, after the above step calculate the value of estimated pi as below and then print the obtained value.
- Pi = 4.0 * ((double)pCircle / (double)(pSquare))
Below is the implementation of the above approach:
Final Estimation of Pi = 3.146600
Time Complexity: O(N*K)
Auxiliary Space: O(1)