Introduction
In our last lesson, we established the theoretical foundation of rejection sampling, a versatile method for drawing samples from complex probability distributions. We saw how it uses a simpler, easy-to-sample "proposal" distribution to generate candidates, which are then accepted or rejected to match the desired "target" distribution.
Now, we will put this theory into practice on a problem of central importance to radiation transport: Compton scattering. Our goal in this lesson is to implement a rejection sampling algorithm to sample from the Klein-Nishina distribution for Compton scattering. Because this interaction is a dominant process for the photons we'll be simulating, mastering this sampling technique is a critical step. The Klein-Nishina formula's complexity makes its cumulative distribution function non-invertible, rendering the inverse transform method useless and making rejection sampling the ideal tool for the job.
The Klein-Nishina Distribution as a Sampling Target
Compton scattering describes the interaction of a photon with a free or loosely bound electron. The outcome is a scattered photon of lower energy and a recoil electron. The probability of scattering into a particular direction is not uniform; it is governed by the Klein-Nishina differential cross section, .
For an incident photon of energy , the differential cross section as a function of the scattering angle is given by:
where is the classical electron radius, and is the energy of the scattered photon, related to the incident energy by the Compton formula:
Here, is the rest mass energy of the electron ( MeV).
The shape of this angular distribution changes significantly with the incident photon energy. At low energies, scattering is nearly symmetric, but as energy increases, it becomes strongly peaked in the forward direction.

Polar (top) and Cartesian (bottom) plots of the Klein-Nishina differential cross section. Notice how for higher incident photon energies (e.g., 1 MeV and 10 MeV), the probability of scattering at small angles ( near 0°) is much higher than for back-scattering ( near 180°).
To use this in a simulation, we need a probability density function (PDF) for the scattering angle, . We obtain this by remembering that the solid angle element is . The PDF is therefore proportional to the cross section multiplied by this geometric factor:
Our task is to draw random samples of from this distribution, which governs the photon's change in direction after a Compton event.
Implementing a Rejection Sampler in Python
Let's build a sampler for . Following the rejection sampling algorithm, we need a proposal distribution and an envelope.
- Target Function : We will use the unnormalized PDF, . We can ignore the leading constant since it will cancel out in the acceptance probability ratio.
- Proposal Distribution : The simplest choice is a uniform distribution over the domain of , which is . So, .
- Envelope: We need a constant such that . Since is constant, this is equivalent to finding a value that is at least as large as the maximum value of our target function, . We then accept a candidate if a uniform random number satisfies .
A complete Python implementation of this procedure is provided in a useful document on simulating gamma rays. This resource contains a general-purpose rejection sampler and the specific Klein-Nishina PDF.
[PDF] Monte Carlo Simulation of Gamma Rays
This PDF provides code snippets that are directly applicable to our task. We will examine the core functions for implementing and testing the rejection sampler.
In the 'Appendix Code' section, first locate the monte_carlos function. This is a general rejection sampler that takes a function p, a domain [x_min, x_max], and an envelope height p_max. Notice its simple while loop structure, which keeps generating candidates until one is accepted. Next, find the definition of the p_theta function. This is the fully normalized Klein-Nishina PDF for the scattering angle \theta (represented as q in the code), where g is the incident energy in units of m_e c^2. The long expression in the denominator is the normalization constant. Finally, observe how these are used to generate and verify samples. Study the code that generates 10,000 samples from p_theta and then plots a histogram of these samples against the analytical p_theta curve. This is a crucial validation step.
Your Turn: Building the Sampler
Now, let's consolidate this into a clear Python script. You can write this code yourself based on the principles we've discussed and the functions from the resource.
First, define the unnormalized Klein-Nishina PDF. Working with the unnormalized version is often simpler, as it avoids the complex integral for the normalization constant. Let's create a function for an incident energy of 1 MeV ().
import numpy as np
import matplotlib.pyplot as plt
def kn_unnormalized_pdf(theta, alpha=1.957):
"""
Unnormalized Klein-Nishina PDF for scattering angle theta.
alpha is the incident energy in units of electron rest mass.
"""
if np.isscalar(theta):
if theta < 0 or theta > np.pi:
return 0.0
else: # if theta is an array
theta = np.clip(theta, 0, np.pi)
# Compton scattering formula for E'/E
e_ratio = 1.0 / (1.0 + alpha * (1.0 - np.cos(theta)))
# Unnormalized differential cross section (ignoring leading constants)
dsigma_domega = e_ratio**2 * (e_ratio + 1.0/e_ratio - np.sin(theta)**2)
# PDF is proportional to d(sigma)/d(Omega) * sin(theta)
return dsigma_domega * np.sin(theta)
Next, create your rejection sampler. This function should accept the target PDF, its domain, and the height of the envelope.
def rejection_sampler(pdf, x_min, x_max, y_max):
"""
Generic rejection sampler for a 1D distribution.
"""
while True:
# 1. Sample candidate x from uniform proposal
x_candidate = np.random.uniform(x_min, x_max)
# 2. Evaluate target function at candidate
y_target = pdf(x_candidate)
# 3. Sample a vertical position under the envelope
y_uniform = np.random.uniform(0, y_max)
# 4. Accept if the point is under the target curve
if y_uniform <= y_target:
return x_candidate
Finally, put it all together. Find the maximum of your unnormalized PDF (you can do this numerically), generate thousands of samples, and plot a histogram to verify your results.
# --- Main script ---
# Set parameters for 1 MeV photon
alpha_1mev = 1.0 / 0.511
# Find the maximum of the PDF to set the envelope height
theta_vals = np.linspace(0, np.pi, 1000)
pdf_vals = kn_unnormalized_pdf(theta_vals, alpha=alpha_1mev)
M_max = np.max(pdf_vals) * 1.01 # Add 1% safety margin
# Generate samples
num_samples = 50000
samples = [rejection_sampler(lambda t: kn_unnormalized_pdf(t, alpha=alpha_1mev), 0, np.pi, M_max) for _ in range(num_samples)]
# --- Verification Plot ---
plt.figure(figsize=(10, 6))
# Plot histogram of samples
plt.hist(np.rad2deg(samples), bins=180, range=(0, 180), density=True, label='Rejection Samples')
# Plot analytical PDF for comparison (normalized)
analytical_pdf = pdf_vals / np.trapz(pdf_vals, theta_vals)
plt.plot(np.rad2deg(theta_vals), analytical_pdf, 'r-', linewidth=2, label='Analytical PDF')
plt.xlabel('Scattering Angle (degrees)')
plt.ylabel('Probability Density')
plt.title('Sampling the Klein-Nishina Distribution (1 MeV)')
plt.legend()
plt.grid(True)
plt.show()
Running this script should produce a histogram that closely matches the shape of the analytical Klein-Nishina curve, confirming that your sampler is working correctly.
Toward a More Efficient Algorithm
The uniform proposal distribution we used is simple but inefficient. The large "rejection area" between the flat envelope and the peaked target function means many samples are discarded, wasting computation time. For production-level Monte Carlo codes, more sophisticated methods are used.
A classic, highly efficient method for sampling the Klein-Nishina distribution was developed by Herman Kahn and refined by others. One such refinement is presented in the following paper. It uses a clever combination of the composition method (splitting the function into parts) and the rejection method to dramatically improve efficiency.
[PDF] arXiv:physics/9709023v1 [physics.comp-ph] 16 Sep 1997
This paper by Hua, Lingenfelter, and Ramaty describes an optimized algorithm for sampling the Compton scattering distribution. We will focus on the method for "cold electrons," which is what we have been considering.
Read the section titled "Compton Scattering on Cold Electrons". First, note the expression for the energy distribution f(r) in Equation (3), where r = E/E'. This is an alternative but equivalent formulation to sampling the angle \theta. Next, carefully study the sampling algorithm itself. Notice that it's a multi-step process involving several random numbers and conditional checks. This is not a simple rejection scheme. It cleverly splits the domain based on the incident energy \epsilon (which is our 2\alpha) and uses different rejection functions for each part. Finally, appreciate the gain in efficiency mentioned in the text. The author notes that the rejection rates for this method are significantly lower than for Kahn's original technique, especially at high energies. This highlights the importance of choosing an efficient algorithm in large-scale simulations.
This advanced algorithm avoids computationally expensive functions like square roots or logarithms and is tailored to the specific shape of the Klein-Nishina distribution, making it far superior to our simple uniform-proposal sampler. While we won't implement it here, being aware of such optimized techniques is crucial for understanding how real-world transport codes achieve high performance.
Conclusion
In this lesson, you have taken a significant practical step, moving from the abstract theory of rejection sampling to a concrete implementation for a fundamental physical process. This bridge between theory and computation is at the heart of building a Monte Carlo simulation.
Key Takeaways:
- The Klein-Nishina distribution, which governs the angle of Compton scattering, cannot be sampled directly with the inverse transform method.
- Rejection sampling provides a robust method for this task. A simple implementation uses a uniform proposal distribution, but this is computationally inefficient.
- We successfully implemented and validated a Python-based rejection sampler for the Klein-Nishina PDF.
- Highly efficient, specialized algorithms like the Kahn-Pei method exist and are used in practice to minimize the rejection rate and speed up simulations.
Preview of the Next Lesson:
So far, we have built the foundational tools for our simulation: sampling the distance to collision, determining the interaction type, and now, sampling the post-collision angle and energy. We are finally ready to assemble these components. In the next module, we will begin writing a full Monte Carlo simulation, starting with the logic for tracking a single particle's history—its "random walk"—from birth to termination.