Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Part 4: Random Sampling - From Theory to Computation

How Nature Computes | Statistical Thinking Module 1 | ASTR 596

San Diego State University

Learning Outcomes

By the end of Part 4, you will be able to:


3.1 Why Random Sampling Matters

Priority: 🔴 Essential Theory tells us distributions exist. But for simulations, we need to generate samples. The challenge: computers only produce uniform random numbers [0,1]. How do we transform these into complex astrophysical distributions?

This is where theory meets computation. Random sampling bridges the gap between:

Monte Carlo Method: Estimating π Through Random Sampling. This comprehensive demonstration shows the foundation technique for all computational astrophysics - transforming complex integrals into simple counting problems using random sampling. Top-left: Monte Carlo dartboard method with 1,000 samples shows random points (teal inside circle, rose outside) thrown at a square containing a unit circle. The π estimate comes from counting: π ≈ 4 × (fraction of points inside circle). Top-right: High density sampling with 10,000 points reveals the method’s statistical nature - more samples give better coverage of the true circle boundary, with accuracy annotation showing typical ~0.5% error. Bottom-left: Error scaling analysis demonstrates the fundamental 1/√N convergence rate that governs all Monte Carlo methods, comparing measured errors (blue circles) against theoretical scaling (dashed rose line) across 6 orders of magnitude in sample size. Bottom-right: Convergence to true value shows how π estimates (teal line) approach the exact value (rose horizontal line) as N increases, with expected ±1σ statistical bounds (gray shaded region). This illustrates the universal trade-off in computational astrophysics: statistical precision scales as 1/√N, meaning 100× more computation yields only 10× better accuracy. The same technique that estimates π also computes stellar opacities, galaxy luminosity functions, and radiative transfer - making this the foundation of modern computational astrophysics.

Figure 1:Monte Carlo Method: Estimating π Through Random Sampling. This comprehensive demonstration shows the foundation technique for all computational astrophysics - transforming complex integrals into simple counting problems using random sampling. Top-left: Monte Carlo dartboard method with 1,000 samples shows random points (teal inside circle, rose outside) thrown at a square containing a unit circle. The π estimate comes from counting: π ≈ 4 × (fraction of points inside circle). Top-right: High density sampling with 10,000 points reveals the method’s statistical nature - more samples give better coverage of the true circle boundary, with accuracy annotation showing typical ~0.5% error. Bottom-left: Error scaling analysis demonstrates the fundamental 1/√N convergence rate that governs all Monte Carlo methods, comparing measured errors (blue circles) against theoretical scaling (dashed rose line) across 6 orders of magnitude in sample size. Bottom-right: Convergence to true value shows how π estimates (teal line) approach the exact value (rose horizontal line) as N increases, with expected ±1σ statistical bounds (gray shaded region). This illustrates the universal trade-off in computational astrophysics: statistical precision scales as 1/√N, meaning 100× more computation yields only 10× better accuracy. The same technique that estimates π also computes stellar opacities, galaxy luminosity functions, and radiative transfer - making this the foundation of modern computational astrophysics.

4.2 The Cumulative Distribution Function (CDF) and Inverse Transform Sampling

Priority: 🔴 Essential The key to sampling from any distribution lies in understanding the cumulative distribution function (CDF) and how it enables the inverse transform method—the most fundamental technique for converting uniform random numbers into samples from any distribution.

Understanding the CDF

The CDF is defined as:

F(x)=P(Xx)=xf(x)dx\boxed{F(x) = P(X \leq x) = \int_{-\infty}^{x} f(x') dx'}

While the probability density function (PDF) f(x) tells us the relative likelihood at each point, the CDF F(x) tells us the accumulated probability up to that point. This accumulation is what makes sampling possible.

To understand why this is so powerful, consider what the CDF actually represents. If you have a PDF f(x) that describes the distribution of stellar masses, then F(m) answers the question: “What fraction of stars have mass less than or equal to m?”

For example, in a stellar population:

Key properties of CDFs:

The Inverse Transform Method

The crucial insight is that the CDF transforms any distribution—no matter how complex—into a uniform distribution on [0,1]. This provides the bridge between uniform random numbers (which computers generate) and any distribution we want.

Visual intuition: Imagine the CDF as a transformation that “stretches” the uniform distribution. Regions where the PDF is large (high probability density) correspond to steep sections of the CDF. When we invert, these steep sections get “compressed” back, allocating more samples to high-probability regions.

Example: Exponential Distribution

Before tackling power laws, let’s see how this works for the exponential distribution (which describes photon path lengths, radioactive decay, and time between stellar collisions):

PDF: f(x)=λeλxf(x) = \lambda e^{-\lambda x} for x ≥ 0

CDF: F(x)=0xλeλxdx=1eλxF(x) = \int_0^x \lambda e^{-\lambda x'} dx' = 1 - e^{-\lambda x}

Inverse: Solve u=1eλxu = 1 - e^{-\lambda x} for x:

Since u and (1-u) are both uniform on [0,1], we can simplify to: x=1λln(u)x = -\frac{1}{\lambda}\ln(u)

# Sample exponential distribution (e.g., photon mean free paths)
def sample_exponential(lambda_param, n_samples):
    u = np.random.uniform(0, 1, n_samples)
    return -np.log(u) / lambda_param

# Example: mean free path of 1 pc
mfp = 1.0  # pc
lambda_param = 1.0 / mfp
path_lengths = sample_exponential(lambda_param, 10000)
print(f"Mean path: {np.mean(path_lengths):.2f} pc")
print(f"Theory: {mfp:.2f} pc")

Power Law Distributions: The Foundation of Astrophysics

Power law distributions appear everywhere in astronomy:

Deriving the sampling formula:

  1. Normalize the PDF: f(x)=(α1)xαxmin1αxmax1αf(x) = \frac{(\alpha-1) x^{-\alpha}}{x_{\min}^{1-\alpha} - x_{\max}^{1-\alpha}} (for α ≠ 1)

  2. Compute the CDF: F(x)=xminxf(x)dx=x1αxmin1αxmax1αxmin1αF(x) = \int_{x_{\min}}^x f(x')dx' = \frac{x^{1-\alpha} - x_{\min}^{1-\alpha}}{x_{\max}^{1-\alpha} - x_{\min}^{1-\alpha}}

  3. Invert to get sampling formula: Set F(x) = u and solve for x: x=[xmin1α+u(xmax1αxmin1α)]1/(1α)\boxed{x = \left[x_{\min}^{1-\alpha} + u(x_{\max}^{1-\alpha} - x_{\min}^{1-\alpha})\right]^{1/(1-\alpha)}}

Special case α = 1: The integral of 1/x is ln(x), so: x=xmin(xmaxxmin)u\boxed{x = x_{\min} \left(\frac{x_{\max}}{x_{\min}}\right)^u}

Sample Size Determines Accuracy in Power Law Distributions. The Salpeter Initial Mass Function (α=2.35) demonstrates how statistical convergence works in practice. Left panel (N=100): Small samples show noisy histograms with poor fits to the theoretical power law—individual random fluctuations dominate. Center panel (N=1,000): Medium samples begin to reveal the underlying distribution structure with better agreement. Right panel (N=10,000): Large samples produce smooth histograms that closely match theory. Statistics boxes show quantitative metrics: mean mass, median mass, and fraction below 1 M☉. This convergence behavior is universal across all Monte Carlo methods—larger samples always yield more accurate results, following the fundamental 1/√N error scaling we learned in Section 4.1.

Figure 2:Sample Size Determines Accuracy in Power Law Distributions. The Salpeter Initial Mass Function (α=2.35) demonstrates how statistical convergence works in practice. Left panel (N=100): Small samples show noisy histograms with poor fits to the theoretical power law—individual random fluctuations dominate. Center panel (N=1,000): Medium samples begin to reveal the underlying distribution structure with better agreement. Right panel (N=10,000): Large samples produce smooth histograms that closely match theory. Statistics boxes show quantitative metrics: mean mass, median mass, and fraction below 1 M☉. This convergence behavior is universal across all Monte Carlo methods—larger samples always yield more accurate results, following the fundamental 1/√N error scaling we learned in Section 4.1.

Implementation and Visualization

The figure above shows our power law sampling in action. Here’s how to implement it yourself:

import numpy as np
import matplotlib.pyplot as plt

def sample_simple_power_law(alpha, x_min, x_max, n_samples):
    """
    Sample from a power law distribution p(x) ∝ x^(-alpha).
    
    This demonstrates the inverse transform method for power laws.
    Special case: alpha = 1 requires logarithmic sampling.
    
    Parameters:
    -----------
    alpha : float
        Power law exponent (positive for decreasing function)
    x_min, x_max : float
        Range of the distribution
    n_samples : int
        Number of samples to generate
        
    Returns:
    --------
    samples : ndarray
        Random samples from the power law
    """
    u = np.random.uniform(0, 1, n_samples)
    
    if abs(alpha - 1.0) < 1e-10:
        # Special case: p(x) ∝ x^(-1)
        # CDF integral gives logarithmic form
        samples = x_min * (x_max/x_min)**u
    else:
        # General case: p(x) ∝ x^(-alpha)
        # Apply the inverse transform formula we derived
        samples = (x_min**(1-alpha) + u*(x_max**(1-alpha) - x_min**(1-alpha)))**(1/(1-alpha))
    
    return samples

# Example: Sample stellar masses with different power laws
fig, axes = plt.subplots(1, 3, figsize=(15, 4))

# Different IMF slopes (Salpeter has alpha = 2.35)
alphas = [1.3, 2.3, 3.5]
x_min, x_max = 0.1, 100  # Solar masses

for ax, alpha in zip(axes, alphas):
    # Generate samples
    samples = sample_simple_power_law(alpha, x_min, x_max, 10000)
    
    # Plot histogram
    bins = np.logspace(np.log10(x_min), np.log10(x_max), 50)
    ax.hist(samples, bins=bins, alpha=0.7, density=True, label='Samples')
    
    # Overlay theoretical distribution
    x_theory = np.logspace(np.log10(x_min), np.log10(x_max), 100)
    # Normalized power law
    if alpha != 1:
        norm = (1-alpha)/(x_max**(1-alpha) - x_min**(1-alpha))
        p_theory = abs(norm) * x_theory**(-alpha)  # abs() for alpha < 1
    else:
        norm = 1/np.log(x_max/x_min)
        p_theory = norm / x_theory
    
    ax.plot(x_theory, p_theory, 'r-', linewidth=2, label='Theory')
    
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlabel(r'Mass $[M_☉])
    ax.set_ylabel('Probability Density')
    ax.set_title(rf'$\alpha = ${alpha}')
    ax.legend()
    ax.grid(True, alpha=0.3)
    
    # Add statistics
    mean_mass = np.mean(samples)
    median_mass = np.median(samples)
    text_str = rf'Mean: {mean_mass:.1f} $M_☉ + '\n' + rf'Median: {median_mass:.1f} $M_☉
    ax.text(0.05, 0.95, text_str, transform=ax.transAxes, 
            verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

plt.suptitle('Power Law Sampling with Different Slopes', fontsize=14)
plt.tight_layout()
plt.show()

# Show how the distribution changes with alpha
print("Effect of power law slope α on stellar mass distribution:")
print(f"{'α':<5} {'Mean [M_☉]':<12} {'Median [M_☉]':<12} {'% below 1 M_☉':<15}")
print("-" * 50)

for alpha in alphas:
    samples = sample_simple_power_law(alpha, x_min, x_max, 10000)
    mean_mass = np.mean(samples)
    median_mass = np.median(samples)
    frac_below_1 = np.sum(samples < 1.0) / len(samples) * 100
    print(f"{alpha:<5.1f} {mean_mass:<12.2f} {median_mass:<12.2f} {frac_below_1:<15.1f}")

Why the Inverse Transform is Powerful

The inverse transform method is the foundation of Monte Carlo sampling because:

  1. It’s exact: Every uniform random number produces exactly one sample from your distribution

  2. It’s efficient: 100% of random numbers are used (no rejections)

  3. It’s deterministic: The same uniform input always gives the same output (useful for debugging)

  4. It works in any dimension: Can be extended to multivariate distributions

However, it requires that you can:

When these conditions aren’t met, you’ll need other methods like rejection sampling (Section 3.6) or Markov Chain Monte Carlo (Project 4).

Example: Exponential distribution (photon path lengths!)

Simple implementation:

# Sample exponential distribution (e.g., photon path lengths)
def sample_exponential(lambda_param, n_samples):
    u = np.random.uniform(0, 1, n_samples)
    # Inverse CDF transform
    return -np.log(1 - u) / lambda_param

# Example: mean free path of 1 pc
mfp = 1.0  # pc
lambda_param = 1.0 / mfp
path_lengths = sample_exponential(lambda_param, 10000)
print(f"Mean path: {np.mean(path_lengths):.2f} pc")
print(f"Theory: {mfp:.2f} pc")

4.6 Rejection Sampling

Priority: 🟡 Standard Path When inverse transform fails, use rejection sampling:

Example: Throw darts at rectangle, keep those under curve.

# Example: Sample from arbitrary distribution
def rejection_sample(f, x_min, x_max, f_max, n_samples):
    """Sample using rejection method"""
    samples = []
    n_tries = 0

    while len(samples) < n_samples:
        x = np.random.uniform(x_min, x_max)
        y = np.random.uniform(0, f_max)
        n_tries += 1

        if y <= f(x):
            samples.append(x)

    efficiency = n_samples / n_tries
    print(f"Efficiency: {efficiency:.1%}")
    return np.array(samples)
Random Sampling Methods: From Uniform to Any Distribution. This comprehensive comparison demonstrates the two fundamental Monte Carlo sampling techniques that bridge the gap between uniform computer-generated random numbers and complex astrophysical distributions. Left panels: Inverse Transform Method applied to exponential distribution shows (top) the theoretical exponential CDF F(x) = 1 - e^(-λx) mapping uniform [0,1] inputs to exponentially distributed outputs, with the dashed line illustrating how uniform input u=0.5 transforms to x=0.35 via the inverse CDF. The (bottom) histogram of 10,000 samples perfectly matches the theoretical exponential PDF f(x) = λe^(-λx) with λ=2. Right panels: Rejection Sampling Method for quadratic distribution demonstrates (top) the “dart-throwing” approach where uniform (x,y) points fill a bounding box, with accepted points (blue, lying under the curve) separated from rejected points (red, above the curve). The (bottom) histogram shows excellent agreement between accepted samples and the theoretical quadratic PDF f(x) = 3x². This figure illustrates why inverse transform is preferred when analytical CDFs exist (100% efficiency, exact sampling) while rejection sampling handles arbitrary distributions at the cost of computational overhead through rejections.

Figure 3:Random Sampling Methods: From Uniform to Any Distribution. This comprehensive comparison demonstrates the two fundamental Monte Carlo sampling techniques that bridge the gap between uniform computer-generated random numbers and complex astrophysical distributions. Left panels: Inverse Transform Method applied to exponential distribution shows (top) the theoretical exponential CDF F(x) = 1 - e^(-λx) mapping uniform [0,1] inputs to exponentially distributed outputs, with the dashed line illustrating how uniform input u=0.5 transforms to x=0.35 via the inverse CDF. The (bottom) histogram of 10,000 samples perfectly matches the theoretical exponential PDF f(x) = λe^(-λx) with λ=2. Right panels: Rejection Sampling Method for quadratic distribution demonstrates (top) the “dart-throwing” approach where uniform (x,y) points fill a bounding box, with accepted points (blue, lying under the curve) separated from rejected points (red, above the curve). The (bottom) histogram shows excellent agreement between accepted samples and the theoretical quadratic PDF f(x) = 3x². This figure illustrates why inverse transform is preferred when analytical CDFs exist (100% efficiency, exact sampling) while rejection sampling handles arbitrary distributions at the cost of computational overhead through rejections.

4.7 Spatial Distributions: The Plummer Sphere

Priority: 🔴 Essential for Project 2 Now that you can sample stellar masses from the Kroupa IMF, you need to place these stars in space. The Plummer sphere is a standard density profile for globular clusters and stellar systems.

The Plummer Profile

The Plummer sphere has density profile:

ρ(r)=3Mtotal4πa3(1+r2a2)5/2\rho(r) = \frac{3M_{total}}{4\pi a^3} \left(1 + \frac{r^2}{a^2}\right)^{-5/2}

where:

This creates a smooth, centrally concentrated distribution that avoids the infinite density at r=0 that plagues some other profiles.

The Sampling Challenge

You can’t sample directly from ρ(r)\rho(r) because density isn’t probability! The key insight: the probability of finding a star between radius rr and r+drr+dr is proportional to the mass in that shell, not the density.

dPρ(r)×(volume of shell)ρ(r)×4πr2drdP \propto \rho(r) \times \text{(volume of shell)} \propto \rho(r) \times 4\pi r^2 dr

So the radial PDF is:

f(r)r2ρ(r)=r2(1+r2a2)5/2f(r) \propto r^2 \rho(r) = r^2 \left(1 + \frac{r^2}{a^2}\right)^{-5/2}

Approach 1: Mass Profile Method

The enclosed mass within radius rr is:

M(<r)=Mtotalr3(r2+a2)3/2M(<r) = M_{total} \frac{r^3}{(r^2 + a^2)^{3/2}}

The cumulative mass fraction (which IS a CDF!) is:

F(r)=M(<r)Mtotal=r3(r2+a2)3/2F(r) = \frac{M(<r)}{M_{total}} = \frac{r^3}{(r^2 + a^2)^{3/2}}

To sample:

  1. Generate uU(0,1)u \sim U(0,1) (this represents a mass fraction)

  2. Solve u=r3(r2+a2)3/2u = \frac{r^3}{(r^2 + a^2)^{3/2}} for rr

  3. Place the star at radius rr with random angular coordinates

Approach 2: Rejection Sampling in 3D

Alternatively, you could:

  1. Generate random positions in a cube containing your cluster

  2. Accept/reject based on the density at that position

  3. But this becomes inefficient for large clusters!

From Radius to 3D Positions

Once you have radius rr:

  1. Generate random direction on sphere:

    • θU(0,π)\theta \sim U(0, \pi) (polar angle)

    • ϕU(0,2π)\phi \sim U(0, 2\pi) (azimuthal angle)

  2. Convert to Cartesian:

    • x=rsinθcosϕx = r \sin\theta \cos\phi

    • y=rsinθsinϕy = r \sin\theta \sin\phi

    • z=rcosθz = r \cos\theta

Or use the simpler method: generate a random unit vector and scale by rr.

Verification

Your sampled positions should reproduce:

  1. The density profile ρ(r)\rho(r) when binned radially

  2. The enclosed mass profile M(<r)M(<r)

  3. The half-mass radius rhalf1.3ar_{half} \approx 1.3a for Plummer

Plummer Sphere Sampling: From 1D CDF to 3D Stellar Positions. This comprehensive demonstration shows how inverse transform sampling creates realistic star cluster initial conditions using 10,000 stellar positions. Top-left: Face-on 2D projection shows the centrally concentrated structure with color-coded radial distances (bright yellow = center, dark purple = outer regions, colorbar spans 0-4 scale radii). Reference circles mark 1a, 2a, and 3a. Top-right: Density profile verification on log-log scale compares our sampled data points (blue) against the theoretical Plummer profile (red line), showing excellent agreement across radius range 0.1-4.0a with normalized density values up to 1.0. Bottom-left: Cumulative mass profile demonstrates that our inverse transform sampling correctly reproduces the theoretical CDF (red curve), with the half-mass radius marked at r₁/₂ = 1.3a where 50% of stars lie within this radius. Bottom-right: Edge-on view reveals the 3D spherical structure, confirming that our sampling method produces realistic spatial distributions for N-body simulations. This validates that the inverse transform method perfectly converts uniform random numbers into physically meaningful 3D stellar positions following the Plummer density law.

Figure 4:Plummer Sphere Sampling: From 1D CDF to 3D Stellar Positions. This comprehensive demonstration shows how inverse transform sampling creates realistic star cluster initial conditions using 10,000 stellar positions. Top-left: Face-on 2D projection shows the centrally concentrated structure with color-coded radial distances (bright yellow = center, dark purple = outer regions, colorbar spans 0-4 scale radii). Reference circles mark 1a, 2a, and 3a. Top-right: Density profile verification on log-log scale compares our sampled data points (blue) against the theoretical Plummer profile (red line), showing excellent agreement across radius range 0.1-4.0a with normalized density values up to 1.0. Bottom-left: Cumulative mass profile demonstrates that our inverse transform sampling correctly reproduces the theoretical CDF (red curve), with the half-mass radius marked at r₁/₂ = 1.3a where 50% of stars lie within this radius. Bottom-right: Edge-on view reveals the 3D spherical structure, confirming that our sampling method produces realistic spatial distributions for N-body simulations. This validates that the inverse transform method perfectly converts uniform random numbers into physically meaningful 3D stellar positions following the Plummer density law.

Part 4 Synthesis: Theory to Computation