Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- We need to estimate the value of pi.
- 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
- 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
- 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)
- We know the equation of circle at origin of radius 1 is: x^2 + y^2 = 1^2=1
- 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.
- so,if we find 10000 points and find that how many is in cirle and how many is in square ie. pi/4
- so,multiple the above value with 4 and return the value of pi.
- */
- #include <bits/stdc++.h>
- #define INTERVAL 10000
- using namespace std;
- int main(){
- int interval, i;
- double rand_x, rand_y, origin_dist, pi;
- int circle_points = 0, square_points = 0;
- srand(time(NULL)); //It will generate different set of random numbers at every program execution not rand() execution.
- for (i = 0; i < (INTERVAL * INTERVAL); i++) {
- rand_x = double(rand() % (INTERVAL + 1)) / INTERVAL; // Randomly generated x and y values
- rand_y = double(rand() % (INTERVAL + 1)) / INTERVAL;
- origin_dist = rand_x * rand_x + rand_y * rand_y; // Distance between (x, y) from the origin
- if (origin_dist <= 1) // Checking if (x, y) lies inside the define circle with R=1
- circle_points++;
- square_points++; // Total number of points generated
- pi = double(4 * circle_points) / square_points; // estimated pi after this iteration
- }
- cout << "\nFinal Estimation of Pi = " << pi; // Final Estimated Value
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement