Estimating PiΒΆ

// pi_estimate.cpp

//
// This code estimates the value of pi using Monte Carlo integration, i.e. it
// simulates throwing darts at a circular dart board, and uses the ratio of
// darts landing in the circle to darts landing outside the circle to estimate
// pi.
//

#include <iostream>
#include <cstdlib>
#include <cmath>
#include "cmpt_error.h"

using namespace std;

// Returns a random number r such that 0.0 <= r <= 1.0
double rand01() {
    return double(rand()) / RAND_MAX;
}

// This function estimates the value of pi by using a quarter circle centered
// at (0, 0). A random (x, y) point in the unit square (with corners (0, 0)
// and (1 ,1)) is chosen, and count is incremented if it's in the circle. The
// the count divided by the total number of points approximates the area of a
// quarter circle with radius 1, and so the area A is A = 4*pi, which
// rearranges to pi = A/4.
void estimate_pi(int num_points) {
    int count = 0;
    for(int i = 0; i < num_points; ++i) {
        double x = rand01();
        double y = rand01();
        double d = sqrt(x*x + y*y);  // distance between (x, y) and (0, 0)
        if (d <= 1.0) {
            count++;
        }
    } // for

    double area_est = double(count) / num_points;
    double pi_est = 4 * area_est;

    cout << "num_points     = " << num_points << "\n";
    cout << "count          = " << count << "\n";
    cout << "estimated area = " << area_est << "\n";
    cout << "pi estimate    = " << pi_est << "\n";
}

int main() {
    estimate_pi(100000);
}