Estimate Pi using Monte Carlo Method

The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.

Hint: The basic equation of a circle is x2 + y2 = r2.

Example:

Output: 3.1528

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int i;
    int nThrows = 0;
    int nSuccess = 0;

    double xy;
    double pi;

    for (i = 0i < 10000i++)
    {
        x = double(rand() % (1000 + 1)) / 1000;
        y = double(rand() % (1000 + 1)) / 1000;

        nThrows++;

        if (x * x + y * y <= 1)
            nSuccess++;
        pi = (4 * (double)nSuccess) / (double)nThrows;
    }
    cout << pi << "\n";

    return 0;
}


No comments:

Post a Comment