Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 42

Monte Carlo Integration

Recommended resources

Introduction

Welcome to our final lesson in this module on the foundations of Monte Carlo simulation. In our previous lessons, we developed the essential tools for sampling from probability distributions, culminating in a practical implementation of rejection sampling for the Klein-Nishina distribution. These techniques allow us to answer the question: "What happens next?" for a simulated particle.

Today, we shift our focus to a broader question: "What is the average behavior of all particles?" This is where Monte Carlo methods truly shine, not just as a way to mimic individual probabilistic events, but as a powerful tool for numerical integration. Our goal for this lesson is to learn how to estimate a definite integral using Monte Carlo sampling and compute the associated statistical uncertainty. This skill is the direct precursor to scoring physical quantities like flux or dose in a transport simulation, which are themselves integrals over the particle's phase space.

The Connection Between Integrals and Averages

At its heart, Monte Carlo integration is a clever application of the Law of Large Numbers. You may recall from basic calculus that the average value of a one-dimensional function over an interval is defined as:

A simple rearrangement gives us an expression for the integral itself:

This equation is the foundation of Monte Carlo integration. It tells us that if we can find a way to estimate the average value of the function, , we can directly estimate the value of the integral.

How do we estimate this average? We can do it statistically. By sampling a large number, , of points uniformly at random from the interval , the Law of Large Numbers tells us that the mean of the function evaluated at these points will approach the true average value:

Substituting this approximation back into our expression for the integral gives us the fundamental formula for Monte Carlo integration:

The following video provides an excellent and accessible walkthrough of this concept and demonstrates its implementation in Python.

Monte Carlo Integration In Python For Noobs

This video, "Monte Carlo Integration In Python For Noobs" from the channel Andrew Dotson, provides a clear, step-by-step introduction to the core idea and a simple implementation.

First, watch the conceptual explanation from the beginning up to the introduction. Pay close attention to how the formula for the average value of a function is transformed into a method for approximating an integral. Next, watch the Python implementation walkthrough, starting from the coding segment. The example calculates the integral of \sin(x) from 0 to \pi, which we know is exactly 2. Observe how the formula we just discussed is translated directly into code.

The Statistical Nature of the Estimate

As you saw at the end of the video segment, if you run the simulation again with a new set of random numbers, you get a slightly different answer. This is a critical feature of Monte Carlo methods: the result is not a single, deterministic number but a statistical estimate drawn from a probability distribution.

If we were to perform the entire Monte Carlo integration many times, each time calculating a new estimate for the integral, and then plot a histogram of all our results, we would see a distribution forming. The Central Limit Theorem, a cornerstone of probability theory, tells us that for a large number of samples , this distribution of estimates will be approximately Gaussian (or normal), centered on the true value of the integral.

The width of this Gaussian distribution quantifies the statistical uncertainty of our estimate. A narrow distribution implies high precision, while a wide distribution implies low precision.

This histogram shows the distribution of Monte Carlo estimates for two different methods. Both are centered around the true value (\(\pi \approx 3.14159\)), but the "Average Function Method" (orange) has a much smaller variance (a narrower distribution) than the "Area Method" (blue), making it a more statistically efficient estimator.

The fundamental question then becomes: how do we calculate the uncertainty of our estimate from a single simulation run of particles?

Quantifying Uncertainty: The Standard Error of the Mean

The answer lies in the Central Limit Theorem. The theorem not only tells us the shape of the distribution of estimates is Gaussian, but it also gives us a precise formula for its standard deviation.

The standard deviation of our estimate of the integral, , which we'll call the statistical error , is given by:

where is the true standard deviation of the function over the interval . This standard deviation is defined as .

This formula reveals the most important (and sometimes limiting) feature of Monte Carlo convergence: the error decreases as . This means to reduce the error by a factor of 10, you must increase the number of samples by a factor of 100. This is a slow rate of convergence compared to deterministic methods like the trapezoidal rule in one dimension, but its power is that this convergence rate is independent of the dimensionality of the integral, which is why Monte Carlo excels for the high-dimensional integrals found in particle transport.

The following document provides a clear derivation of this behavior and the resulting error formula.

[PDF] Monte Carlo simulations in physics

This document offers a concise, physics-oriented explanation of Monte Carlo integration and its error analysis.

First, read the section "Why error is ∝ 1/√N?" (starts on page 10). This section uses Fourier transforms to show how the distribution of the sample mean, z_N, becomes a Gaussian with a standard deviation of \sigma/\sqrt{N}. As a physicist, you may appreciate the rigor of this derivation, but focus on the final result: the standard deviation of the mean is the standard deviation of the underlying distribution divided by the square root of the number of samples. Next, read the summary section "In summary: error in MC integration" (page 11). This provides the key practical formula for the error: \sigma_N = V \sqrt{\frac{\langle f^2 \rangle - \langle f \rangle^2}{N}}. Critically, it points out that since we don't know the true expectation values \langle f \rangle and \langle f^2 \rangle, we must estimate them from our samples.

This log-log plot shows the percentage error of a Monte Carlo simulation as a function of the number of samples. The "real error" (red squares) fluctuates but closely follows the "predicted" \(1/\sqrt{N}\) trend line (dashed black line), beautifully illustrating the theoretical convergence rate.

Your Turn: Implementation with Error Calculation

Now, let's put theory into practice. We will expand the Python code for integrating to also compute the statistical error from a single run. The process involves calculating not only the average of but also the average of .

Here is the complete algorithm for estimating an integral and its uncertainty from a single batch of samples:

  1. Generate random numbers, , uniformly distributed in .
  2. For each , compute and .
  3. Compute the estimate of the sample mean of : .
  4. Compute the estimate of the sample mean of : .
  5. Calculate the estimate of the integral: .
  6. Calculate the sample variance of the function : . (The factor is Bessel's correction, which provides an unbiased estimate of the variance).
  7. Calculate the standard error of the mean: .
  8. Calculate the final error on the integral: .

Below is a Python script that implements this full procedure. Take your time to read through it and connect each line of code to the steps outlined above.

import numpy as np

def monte_carlo_integrate(func, a, b, num_samples=10000):
    """
    Estimates the definite integral of a function using Monte Carlo sampling
    and computes the statistical uncertainty.
    
    Args:
        func (callable): The function to integrate.
        a (float): The lower limit of integration.
        b (float): The upper limit of integration.
        num_samples (int): The number of random samples to use.
        
    Returns:
        tuple: A tuple containing the integral estimate and its standard error.
    """



    # 1. Generate random samples
    x_samples = np.random.uniform(a, b, num_samples)
    



    # 2. Evaluate the function at the sample points
    f_samples = func(x_samples)
    



    # 3. Compute the sample mean of f
    f_mean = np.mean(f_samples)
    



    # 4. Compute the sample mean of f^2
    f_sq_mean = np.mean(f_samples**2)
    



    # 5. Calculate the integral estimate
    integral_estimate = (b - a) * f_mean
    



    # 6. Calculate the sample variance of the function (with Bessel's correction)
    # The np.var function with ddof=1 calculates the sample variance directly.
    # sample_variance = (f_sq_mean - f_mean**2) * (num_samples / (num_samples - 1))
    sample_variance = np.var(f_samples, ddof=1)




    # 7. Calculate the standard error of the mean
    standard_error = np.sqrt(sample_variance / num_samples)
    



    # 8. Calculate the error on the integral
    integral_error = (b - a) * standard_error
    
    return integral_estimate, integral_error


```grasp
{
  "type": "exercise",
  "id": "9f7632c2-f691-4331-86bf-c10c8fb2093c"
}

--- Example Usage ---


Define the function to integrate: sin(x)

def sin_func(x):
return np.sin(x)


Set integration limits and number of samples

a = 0
b = np.pi
N = 100000


Perform the integration

integral_val, error_val = monte_carlo_integrate(sin_func, a, b, num_samples=N)


The true value of the integral is 2.0

print(f"Number of samples: {N}")
print(f"Integral estimate: {integral_val:.6f}")
print(f"Statistical error: {error_val:.6f}")
print(f"Result: {integral_val:.6f} +/- {error_val:.6f}")

Try running the script yourself. You will see that the estimate is close to 2.0, and the `error_val` gives you a formal, one-sigma ($\approx 68\%$ confidence interval) range for your result. Experiment by changing `N` to $10^4$ and $10^6$. You should see the error decrease by a factor of roughly $\sqrt{10}$ each time, just as predicted.


```grasp
{
  "type": "exercise",
  "id": "fe0b0c82-48d8-47d6-9310-c2389d91ce78"
}

Conclusion

In this lesson, we have moved from sampling individual events to estimating a bulk property—a definite integral—and, crucially, how to assess the quality of that estimate. This forms the final cornerstone of our foundation in Monte Carlo methods.

Key Takeaways:

  • Monte Carlo integration leverages the Law of Large Numbers to approximate an integral by calculating the average value of the integrand over a set of random points.
  • The estimate produced by a Monte Carlo calculation is a random variable that, for a large number of samples , is drawn from a Gaussian distribution centered on the true value.
  • The statistical error (standard deviation) of the estimate decreases with the square root of the number of samples, .
  • It is possible to estimate both the integral and its statistical uncertainty from a single simulation run by calculating the sample mean and sample variance of the function values.

Preview of the Next Lesson:
With this, we conclude our module on the foundations of Monte Carlo. You are now equipped with the essential statistical machinery. In the next module, we will begin our primary task: Monte Carlo Particle Transport Simulation. We will assemble the pieces we've learned—sampling distances, interaction types, and scattering kinematics—into a coherent algorithm that simulates the "random walk" of a particle through a material. The integration technique you learned today will be the basis for scoring, or "tallying," the quantities of interest, like particle flux, from these simulated particle histories.