Introduction
In our last lesson, we successfully assembled the core engine of a Monte Carlo transport code: a Python function, simulate_photon_history, capable of tracing the complete random walk of a single photon from its source to its termination. This function encapsulates the fundamental physics of transport and interaction. However, the simulation of a single particle, while illustrative, yields only one arbitrary outcome from a vast space of possibilities. To derive meaningful physical quantities, we must aggregate the results from a great many such histories.
This lesson bridges the gap between a single random walk and a full-scale simulation. We will wrap our single-history function within an outer loop to run a "batch" of thousands or millions of source photons. By doing this, we leverage the Law of Large Numbers: as the number of simulated particles increases, the average behavior of our sample converges to the true physical expectation. You will learn how to structure this batch simulation, aggregate the outcomes, and understand the statistical foundation that makes this method so powerful.
From a Single History to a Batch Simulation
The transition from simulating one particle to many is conceptually straightforward. We simply execute the simulate_photon_history function repeatedly, each time starting with a fresh source particle, and collect the results. The overall process for a batch simulation follows a clear structure.

This flowchart shows the life of one photon. In a batch simulation, we simply execute this entire process N times for N different source photons.
This procedure of looping over a set number of primary particles is the standard starting point for any Monte Carlo transport code.
[PDF] Introduction to the Monte Carlo simulation of radiation transport
This presentation from CERN outlines the canonical steps of a Monte Carlo simulation. We will now focus on implementing the outer loop that drives the entire process.
Please review the slide titled "Basic Monte Carlo simulation algorithm". Notice that the very first step is to "Loop over np primary events". Our previous lesson implemented steps 3-10 for a single event; today, we implement step 1, which orchestrates the entire simulation.
The result of running a large batch of particles is a rich dataset that can be used to visualize particle behavior and compute physical quantities with statistical confidence. For example, the image below shows a simulation of 500,000 electrons in a cylindrical phantom. This level of detail is only possible by aggregating many individual histories.

A Monte Carlo simulation performed in Python with n_part=500000 electrons. (a) shows the setup code, (b) the 3D particle tracks, and (c) the resulting 2D distribution of deposited energy, a statistically converged result known as a tally.
Implementing the Batch Loop and Aggregating Results
Let's build the Python code to manage a batch of histories. We will define the total number of histories to run, initialize counters for the possible outcomes (transmission, reflection, absorption), and then loop. Inside the loop, we will call our existing simulate_photon_history function and update the appropriate counter based on its return value.
Here is how you can structure the main part of your simulation script:
# Assume simulate_photon_history and its helpers are defined as in the previous lesson.
import numpy as np
# --- (Insert helper functions and simulate_photon_history here) ---
def run_batch_simulation(num_histories, slab_thickness, energy_cutoff, initial_energy):
"""
Runs a batch of photon histories and returns the aggregated results.
"""
# 1. Initialize counters for each termination type
n_transmitted = 0
n_reflected = 0
n_absorbed_interaction = 0
n_absorbed_ecutoff = 0
n_other = 0 # For errors or unexpected outcomes
# Define the source particle template. It will be reset for each history.
source_particle_template = {
'pos': np.array([0.0, 0.0, 0.0]),
'dir': np.array([0.0, 0.0, 1.0]),
'energy': initial_energy,
'is_alive': True
}
# 2. Loop over the total number of histories
print(f"Running simulation for {num_histories} histories...")
for i in range(num_histories):
# Create a new particle for this history
particle = source_particle_template.copy()
# Run the single-particle simulation
termination_reason = simulate_photon_history(particle, slab_thickness, energy_cutoff)
# 3. Tally the result
if termination_reason == "Transmitted":
n_transmitted += 1
elif termination_reason == "Reflected":
n_reflected += 1
elif termination_reason == "Absorbed (interaction)":
n_absorbed_interaction += 1
elif termination_reason == "Absorbed (E-cutoff)":
n_absorbed_ecutoff += 1
else:
n_other += 1
# 4. Normalize results to get probabilities
transmittance = n_transmitted / num_histories
reflectance = n_reflected / num_histories
absorption_interaction = n_absorbed_interaction / num_histories
absorption_ecutoff = n_absorbed_ecutoff / num_histories
# Pack results into a dictionary
results = {
"Transmittance": transmittance,
"Reflectance": reflectance,
"Absorption (interaction)": absorption_interaction,
"Absorption (E-cutoff)": absorption_ecutoff,
"Total Absorption": absorption_interaction + absorption_ecutoff,
"Sum Check": transmittance + reflectance + absorption_interaction + absorption_ecutoff
}
return results
# --- Main execution block ---
if __name__ == '__main__':
# Simulation Parameters
NUM_HISTORIES = 100000
SLAB_THICKNESS = 10.0 # cm
ENERGY_CUTOFF = 0.01 # MeV
SOURCE_ENERGY = 1.0 # MeV
final_results = run_batch_simulation(NUM_HISTORIES, SLAB_THICKNESS, ENERGY_CUTOFF, SOURCE_ENERGY)
print("\n--- Simulation Complete ---")
for key, value in final_results.items():
print(f"{key}: {value:.6f}")
This structure is a universal pattern in Monte Carlo codes. The resource from Scratchapixel demonstrates the exact same logic, using C++ to count the number of reflected (Rd) and transmitted (Tt) photons over many histories.
Monte Carlo Methods in Practice - Scratchapixel
This article provides a complete practical walkthrough, including the transition from a single particle to a full simulation.
First, read the paragraph that introduces the concept of a batch simulation, starting from this point. It presents pseudocode for an outer loop that runs for nphotons and initializes counters for reflectance, transmittance, and absorption. Then, examine the final C++ code implementation in the section that begins near the end. Pay particular attention to the MCSimulation function. You will see the for loop running up to nphotons, the initialization of Rd and Tt counters, and the final normalization (Rd * scale, Tt * scale). This structure directly parallels the Python code we have just written.
The Statistical Power of Batch Simulations
Running a large number of histories is not just about getting a more "accurate" answer; it's about being able to quantify the uncertainty in that answer. Each history is an independent random sample. The Central Limit Theorem tells us that the distribution of the average of these samples will approach a Gaussian distribution, and the standard deviation of this averageβour statistical uncertaintyβdecreases with the square root of the number of samples, .
This relationship is a fundamental law of Monte Carlo simulation. To reduce the statistical error by a factor of 2, you must run 4 times as many histories. To reduce it by a factor of 10, you need 100 times the computational effort.
[PDF] Introduction to the Monte Carlo simulation of radiation transport
This presentation explains the statistical basis for Monte Carlo estimation.
Please read the sections on "Statistical uncertainties" and "Single-history vs batch statistics". Pay close attention to the conclusion that the statistical uncertainty scales as 1/\sqrt{N}. Also, note the important recommendations for running simulations in batches (or cycles) to evaluate the variance and ensure reliable results. Quoting a result without its uncertainty is generally considered meaningless in this field.
The following video provides a practical demonstration of building a batch simulation and using the results to compute simple tallies.
Computational Physics Video 31 - Writing a Monte Carlo Radiation Transport Code
This video walks through writing a Monte Carlo code in MATLAB, but the principles are identical. It clearly shows the transition from a single history to a batch.
First, watch the section where the author implements a for loop to run n_particles (histories). Notice how the single-history code is nested inside this outer loop, and the final positions are stored for each particle. Next, observe how the results from the batch are used to calculate a "tally"βin this case, counting how many particles travel beyond a certain distance. This is analogous to our counting of transmitted and reflected particles.
Your Complete Simulation Code
By combining the run_batch_simulation function with the simulate_photon_history function and its helpers from the previous lesson, you now have a complete, functional Monte Carlo code. I encourage you to experiment by changing NUM_HISTORIES from 100 to 1,000,000. You will observe that the calculated values for transmittance and reflectance fluctuate significantly for small N but stabilize as N grows, demonstrating the convergence predicted by the Law of Large Numbers.
Conclusion
In this lesson, you have taken the crucial step from simulating a single particle's journey to running a full-scale batch simulation. This elevates our program from a simple physics demonstrator to a powerful computational tool capable of producing statistically robust estimates of physical quantities.
Key Takeaways:
- A Monte Carlo batch simulation is implemented by placing a single-history simulation function inside a loop that runs for a large number of histories ().
- Results from each history are aggregated (e.g., by incrementing counters) to compute average quantities like transmittance or reflectance.
- The statistical uncertainty of a Monte Carlo estimate decreases proportionally to , a consequence of the Central Limit Theorem. This makes large batch sizes essential for achieving high precision.
- A complete simulation script integrates parameter definitions, helper functions, the single-history engine, and a main batch-driving loop.
Preview of the Next Lesson:
So far, we have only tallied simple outcomes like transmission and reflection. To make our simulation truly useful for dosimetry, we need to calculate more complex physical quantities within the simulation volume itself. In the next lesson, "Implement track-length, collision, and surface-crossing estimators to score cell-averaged scalar flux," we will introduce the concept of "estimators" or "tallies"βthe specific techniques used to score quantities like particle flux, which is the necessary precursor to calculating kerma and dose.