Introduction
In our previous lesson, we established the three fundamental ways a particle's simulated life can end: absorption, escape, or falling below an energy cutoff. These events form the "stop" conditions for the main loop of our Monte Carlo simulation. Now, we will build the core of that loop: the transport step. This is where the particle actually moves through the simulated world.
This lesson will guide you through implementing particle tracking within a slab geometry. This simple, one-dimensional setup is the foundation of many radiation transport problems. You will learn how to calculate the distance to the next material boundary along a particle's path and how to use this information, in conjunction with the sampled distance to collision, to determine whether the particle interacts within its current region or crosses into a new one. By the end, you'll have the complete logic for moving a particle from one event to the next.
The Central Logic: Interaction vs. Boundary Crossing
At any point in its journey, a particle at position moving in direction faces two competing possibilities:
- It will travel some distance and undergo a physics interaction (scattering or absorption).
- It will travel some distance and hit a geometric boundary.
The core of the transport algorithm is to determine which of these happens first. The process within each step of our simulation's while loop is as follows:
- Sample the distance to the next collision, let's call it . As we've seen, this is sampled from an exponential distribution: , where is the total macroscopic cross section of the current material.
- Calculate the distance to the nearest geometric boundary along the particle's current direction . Let's call this .
- Compare these two distances:
- If , the particle interacts before reaching the boundary. We advance the particle by the distance , update its position to , and then simulate the interaction (e.g., absorption check, Compton scatter).
- If , the particle reaches the boundary first. We advance the particle to the boundary by the distance , update its position to , and then process the boundary crossing. This typically involves updating the particle's current region and, consequently, the material properties (, etc.) for the next step. If the new region is a vacuum, the particle escapes and its history is terminated.
The following flowchart, which you saw in the previous lesson, illustrates this loop. Our focus today is on the "Compute new position" step and the "Did the photon exit?" check, which are fundamentally linked.

Calculating the Distance to a Boundary
The main technical challenge in this process is calculating . For our slab geometry, defined by two infinite parallel planes, this is a straightforward geometric problem. Let's define our slab to exist between and .
The following resource from Scratchapixel provides a clear, practical guide to implementing this calculation. It uses similar triangles to derive the distance to the boundary, which is a very intuitive approach.
Monte Carlo Methods in Practice - Scratchapixel
This article provides a step-by-step guide to building a Monte Carlo simulation. We will focus on the section that deals with particle movement and boundary checks.
First, review the section titled "Principle of the Experiment: Let's Simulate!". Pay attention to the decision tree, which outlines the logic we are implementing. Next, in the same section, read the part explaining how to sample the free path length, beginning from "This says that the probability". This recaps the sampling method for s_{coll}. Finally, and most importantly, study the logic for checking the boundary. Start reading from the paragraph that begins "Next, we will move the photon". This section derives the exact formulas we need for s_{bound} and shows how to compare it with the sampled interaction distance.
As the article explains, if a particle is at position with a normalized direction vector , the distance to the top or bottom plane of the slab is determined by its direction component :
- If (particle is moving "down" towards the plane), the distance to that boundary is .
- If (particle is moving "up" towards the plane), the distance to that boundary is . Note that since is negative, will be positive.
- If , the particle is moving parallel to the slab faces. It will never intersect the top or bottom boundary, so we can consider .
The geometry for this calculation is shown clearly in the diagram below. The relationship is derived from similar triangles, where the ratio of the hypotenuse to the vertical side of the triangle is constant: . Since the direction vector is normalized (i.e., ), this simplifies to .

A More Formal Approach and Numerical Considerations
While the Scratchapixel article provides an excellent practical implementation, your background in physics warrants a look at the more formal and robust methods used in production-grade Monte Carlo codes. The foundational EGSnrc report by Alex Bielajew provides exactly this. It formalizes the distance calculation, which he terms HOWFAR, and discusses critical issues of numerical precision.
[PDF] Geometry Modeling for Monte Carlo Particle Transport
This report is a classic reference on the geometric aspects of Monte Carlo transport. It provides a rigorous foundation for what we are implementing.
First, read the Introduction (from the start) to understand the formal definitions of HOWFAR (distance to intersection) and HOWNEAR. Our s_{bound} is an instance of HOWFAR. Next, read Section 2, "Boundary crossing" (the entire section). This is a crucial section that explains why floating-point inaccuracies can cause "undershoot" or "overshoot" at boundaries and how a robust geometry algorithm must handle these cases. This is a topic often omitted in introductory tutorials but is essential for writing reliable code. Finally, read subsection 4.1.1, "HOWFAR?" under the "Planes" section (this whole subsection). This section provides the general case-by-case logic for calculating the distance to a plane, which is exactly what we need for our slab geometry.
The key insight from the Bielajew paper is that computers have finite precision. When we move a particle to a boundary, its final floating-point position may be slightly before the boundary ("undershoot") or slightly after ("overshoot"). A naive algorithm can get stuck in loops or make incorrect decisions if it doesn't account for this.
A robust strategy, as outlined in the paper, involves maintaining a "logical" state of which region the particle is in, and using that to resolve ambiguities. For example, if a particle just crossed from region 1 to region 2 but, due to undershoot, its coordinates are still numerically in region 1, and it then scatters back towards the boundary, the code must be smart enough to return a distance of 0 and move it cleanly into region 1, rather than calculating a small negative distance which would be nonsensical.
For our implementation, we'll stick to the simpler logic for now, but it's critical to be aware of these potential pitfalls in any serious Monte Carlo code development.
Python Implementation Sketch
Let's outline how you would structure this logic in a Python function. We assume you have a particle object or dictionary that stores its state (pos, dir, energy, region_index, is_alive).
import numpy as np
def transport_step(particle, geometry):
"""
Performs one transport step for a particle.
Moves it to either the next collision or the next boundary.
"""
# 1. Get material properties for the particle's current region
current_region = geometry.regions[particle.region_index]
sigma_t = current_region.get_sigma_t(particle.energy)
if sigma_t <= 0:
# Cannot interact in this region (e.g., a vacuum)
s_coll = np.inf
else:
# 2. Sample distance to next collision
s_coll = -np.log(np.random.rand()) / sigma_t
# 3. Calculate distance to nearest boundary
s_bound, exit_region_index = geometry.distance_to_boundary(
particle.pos, particle.dir, particle.region_index
)
# 4. Compare distances and act
if s_coll < s_bound:
# Interaction happens before boundary crossing
particle.pos += s_coll * particle.dir
# Next, you would simulate the interaction itself
# (e.g., absorption vs. scattering)
# We will integrate this in the next lesson.
print(f"Interaction at {particle.pos}")
else:
# Boundary crossing happens first
particle.pos += s_bound * particle.dir
if exit_region_index is None: # This signifies exiting the world
particle.is_alive = False
print(f"Particle escaped at {particle.pos}")
else:
# Update the particle's region
particle.region_index = exit_region_index
print(f"Particle crossed into region {exit_region_index} at {particle.pos}")
# You would need a simple geometry class to support this
class SlabGeometry:
def __init__(self, regions, boundaries):
self.regions = regions # A list of material objects
self.boundaries = boundaries # e.g., [0.0, 5.0, 10.0] for a two-layer slab
def distance_to_boundary(self, pos, direction, region_idx):
# Implementation of the logic described in the lesson
# This function would find which boundary is next along the path
# and return the distance and the index of the region on the other side.
# ... (implementation details omitted for brevity)
pass
This Python sketch shows the clear separation of concerns: sampling physics (s_coll) versus calculating geometry (s_bound) and then making a decision. The distance_to_boundary method would contain the logic using the (z_boundary - p_z) / u_z formula.
Conclusion
In this lesson, we have detailed the essential algorithm for particle tracking in a slab geometry. You now understand the core logic of comparing the sampled distance-to-collision with the calculated distance-to-boundary to decide a particle's next move. We have explored both a practical, intuitive derivation and a more formal, robust approach used in production codes.
Key Takeaways:
- Particle transport is a competition between interaction and boundary crossing.
- The distance to a plane boundary in a slab geometry can be calculated with the simple formula .
- The smaller of and determines the particle's step length and what event occurs next.
- Robust implementation requires careful handling of floating-point inaccuracies at boundaries, a concept critical for reliable simulations.
Preview of the Next Lesson:
We have now examined all the individual components needed to simulate a single particle history: sampling the initial state, transporting the particle, handling interactions, and terminating the history. In our next lesson, "Write a Python function that simulates the complete life cycle of a single photon in a slab geometry," we will finally assemble all these pieces into one cohesive function, creating our first end-to-end particle simulation.