Chapter 135

Home

Monte Carlo Simulation

Monte Carlo methods estimate values by running many random trials. Used when exact computation is intractable — estimating π, computing expected values in complex games, or evaluating AI positions.

Estimating π via Monte Carlo

C++ — Monte Carlo π estimation

double estimate_pi(int trials = 1000000) {
    int inside = 0;
    for (int i = 0; i < trials; i++) {
        double x = (double)rand() / RAND_MAX;
        double y = (double)rand() / RAND_MAX;
        if (x * x + y * y <= 1) inside++;
    }
    return 4.0 * inside / trials;
}

// Error decreases as 1/√trials. 1M trials → ~0.1% accuracy.