Calculating Pi using Monte Carlo method

closed account (iv0fGNh0)
Hi, im trying to write code to calculate pi using the monte carlo method, but for some reason even though the code compiles, nothing happens. what should happen is a random coordinate should be generated, the distance from the origin should then be calculated, if this is greater than 1, its disregarded, but the n increases (total throws) and if it is less than 1, the number of hits (d) and total throws (n) should both increase, it should then calculate pi using the formula i've used. Finally, the loop for calculating pi should terminate once either of the conditions I've used have been met.

thanks in advance for any help
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
40
41
#include <iostream>
#include <stdlib.h>
#include <math.h>

using namespace std;

double get_pi(double accuracy)
{
    int n = 0, d = 0;
    double x, y, latest_pi = 0;
    double distance_from_origin = 0;

    do
    {   x = 0;
        y = 0;
        x = rand()%100;
        y = rand()%100;
        distance_from_origin = (sqrt(x*x)) + (sqrt(y*y));
        if (distance_from_origin < 1.0)
        {
            d++;
            n++;
        }
        else
        {
            n++;

        }
        latest_pi = 4*(d+1)/(n+1);

    }
    while((d < 100) || (4/(n+1) < accuracy/100));

    return latest_pi;
}

int main()
{
    cout << get_pi(1);
}
Hi,

Line 18 is incorrect: sqrt(x*x) = x, your expression is not pythagoras.

Line 29 and 32 has integer division. As the d and n increase the result becomes zero. I like to put digits before and after the decimal point, to reinforce the idea that the number is a double, and help avoid integer math.

I would rather have the accuracy be 0.01 rather than 1 which is divided later.

If you wish to use rand, you need to seed it with srand

Good Luck !!

Topic archived. No new replies allowed.