Advertisement
imashutosh51

Estimating the value of Pi using Monte Carlo

Nov 7th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. /*
  2. We need to estimate the value of pi.
  3. Area of cirle of radius r is : pi*r^2     ie. -1 to 1 on the x axis and -1 to 1 on y axis
  4. Area of square of the same size : (2*r)^2=4r^2  ie. -1 to 1 on x-axis and -1 to 1 on y axis
  5. so,(Area of cirle of radius r /Area of square of same size) == (pi/4)  == (number of points in circle/number of points in square)
  6. We know the equation of circle at origin of radius 1 is: x^2 + y^2 = 1^2=1
  7. so if our -1<=x<=1 && -1<=y<=1 then that point will definitely come inside the square but can go outside the circle also.
  8. so,if we find 10000 points and find that how many is in cirle and how many is in square ie. pi/4
  9. so,multiple the above value with 4 and return the value of pi.
  10. */
  11.  
  12. #include <bits/stdc++.h>
  13. #define INTERVAL 10000
  14. using namespace std;
  15. int main(){
  16.     int interval, i;
  17.     double rand_x, rand_y, origin_dist, pi;
  18.     int circle_points = 0, square_points = 0;
  19.     srand(time(NULL));  //It will generate different set of random numbers at every program execution not rand() execution.
  20.     for (i = 0; i < (INTERVAL * INTERVAL); i++) {
  21.         rand_x = double(rand() % (INTERVAL + 1)) / INTERVAL;        // Randomly generated x and y values
  22.         rand_y = double(rand() % (INTERVAL + 1)) / INTERVAL;
  23.         origin_dist = rand_x * rand_x + rand_y * rand_y;   // Distance between (x, y) from the origin
  24.  
  25.         if (origin_dist <= 1)       // Checking if (x, y) lies inside the define circle with R=1
  26.             circle_points++;
  27.  
  28.         square_points++;   // Total number of points generated
  29.  
  30.         pi = double(4 * circle_points) / square_points;  // estimated pi after this iteration
  31.     }
  32.     cout << "\nFinal Estimation of Pi = " << pi;   // Final Estimated Value
  33.     return 0;
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement