Monte Carlo method for pi

Hey all, I am trying to use the monte carlo method to determine pi. I think there is an issue with the math I am using but I'm not sure... The program runs, but it's not correct. Can anyone see where I'm wrong? Thanks!

Also, When I run the Random Number Generator, I had to run a "test" one as well, in order for the coord_x to randomize (or else I would get the same number over and over.... No idea why...
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  /*

*/

#include <iostream>
#include <cstdlib>      //defines rand(), srand(), RAND_MAX
#include <ctime>        //defines ctime() for random numbers
#include <cmath>        //defines math functions
using namespace std;

//calculates the distance of the dart from the origin
double dist(double x, double y)
{
    double throwDist;
    throwDist = sqrt(x*x) + sqrt(y*y);  //Euclidean Distance Formula from point (0,0)
    return throwDist;
}
//calculates pi using number of darts thrown in the circle vs all darts thrown
double pie(int numThrows, double a)
{
    double pieValue = a / numThrows;
    return pieValue;
}
int main()
{
    double coord_x, coord_y, test;
    srand(time(NULL));      //creates the seed time
    test = rand() / double(RAND_MAX);
    double throwDist;       //distance from the origin
    double a = 0;              //times a dart ends up inside the circle
    int numThrows;          //times to throw the dart
    cout<< "Enter how many time to throw the dart: ";
    cin>> numThrows;

    //creates 2 random numbers 'n' times
    for(int i = 1; i <= numThrows; i++)
    {
        coord_x = (double)rand() / (RAND_MAX);
        coord_y = (double)rand() / (RAND_MAX);
        throwDist = dist(coord_x, coord_y);
        //counts how often the dart is thrown inside the circle
        if(throwDist <= 1)
        {
            a++;
        }
    }
    double pieCalc = pie(numThrows, a);
    cout<< "The value of PI is: " << pieCalc;
return 0;
}









Last edited on
Two problems:
1) the distance is sqrt(x*x+y*y) on line 15
2) since you only choose positive x and y, you only choose points in one quarter of the circle. So you need to multiply your pieCalc by 4 on line 48
Topic archived. No new replies allowed.