perm_identity Estimating the value of Pi using Monte Carlo

This code is not giving me a value, I need some help to whatI'm doing wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
using namespace std;

int main()
{
    int i;
    double rand_x, rand_y, origin_dist, pi;
    int circle_points = 0, square_points = 0;
    srand(time(NULL));
    
    for (i = 0; i < RAND_MAX; i++) {
        
        rand_x = (double)rand() / (RAND_MAX);
        rand_y = (double)rand() / (RAND_MAX);
        origin_dist = sqrt(rand_x * rand_x + rand_y * rand_y);
  
        if (origin_dist <= 1)
            circle_points++;
        
        square_points++;
        
        if (i < 20)
            getchar();
         pi = double(4 * circle_points) / square_points;
        cout << rand_x << " " << rand_y << " " << circle_points
        << " " << square_points << " - " << pi << endl << endl;
        
    }
    

    cout << "\nFinal Estimation of Pi = " << pi;
    
    return 0;
}
Why would you pick RAND_MAX as your loop limit? That's bizarre.
Try something like 1000000.
And get rid of the getchar and cout inside the loop.
Also, you don't need the sqrt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
    srand(time(0));
    const int square_points = 10000000;
    int circle_points = 0;
    
    for (int i = 0; i < square_points; ++i) {
        double x = rand() / double(RAND_MAX);
        double y = rand() / double(RAND_MAX);
        if (x * x + y * y <= 1.0)
            circle_points++;
    }

    cout << "\nFinal Estimation of Pi = "
         << double(4 * circle_points) / square_points << '\n';
}

Last edited on
Topic archived. No new replies allowed.