Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/optional/scientific-computing/scientific-computing.ipynb

View source on GitHub

Scientific Computing Pitfalls#

This course teaches you to build, test, and distribute Python packages. But scientific software has failure modes that general software does not. A web application that returns a slightly wrong number is buggy. A scientific package that returns a slightly wrong number may invalidate a research conclusion.

This module covers three categories of pitfalls specific to scientific computing: floating-point arithmetic, physical units, and validation against known results. These are the places where AI-generated code is most likely to be subtly wrong — the code runs, the tests pass, but the science is incorrect.

Section 1: Floating-Point Arithmetic#

Why 0.1 + 0.2 != 0.3#

Computers represent numbers in binary (base 2). Just as 1/3 cannot be represented exactly in decimal (0.333…), many common decimal fractions cannot be represented exactly in binary. The number 0.1 in binary is a repeating fraction, so it gets rounded to the nearest representable value.

# This is not a bug — it is how floating-point arithmetic works
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
# See the actual stored value
print(f"{0.1:.20f}")
print(f"{0.3:.20f}")
print(f"{0.1 + 0.2:.20f}")

Machine Epsilon#

Machine epsilon is the smallest number ε such that 1.0 + ε != 1.0 in floating-point arithmetic. For 64-bit floats (Python’s default), this is approximately 2.2 × 10⁻¹⁶.

import numpy as np

# Machine epsilon for different float types
print(f"float64 epsilon: {np.finfo(np.float64).eps}")
print(f"float32 epsilon: {np.finfo(np.float32).eps}")

# Consequence: adding a tiny number to a large number loses the tiny number
large = 1e16
small = 1.0
print(f"\n{large} + {small} = {large + small}")
print(f"Lost the addition: {large + small == large}")

Catastrophic Cancellation#

When you subtract two nearly equal numbers, the significant digits cancel and you are left with the rounding errors. This is called catastrophic cancellation and it is one of the most common sources of numerical bugs.

# Example: computing the variance using the naive formula
# Var(X) = E[X^2] - (E[X])^2
# This is mathematically correct but numerically unstable

def naive_variance(data):
    """Numerically unstable variance calculation."""
    n = len(data)
    mean_sq = sum(x**2 for x in data) / n
    sq_mean = (sum(data) / n) ** 2
    return mean_sq - sq_mean  # Catastrophic cancellation here!


def stable_variance(data):
    """Numerically stable variance using Welford's algorithm."""
    n = 0
    mean = 0.0
    M2 = 0.0
    for x in data:
        n += 1
        delta = x - mean
        mean += delta / n
        delta2 = x - mean
        M2 += delta * delta2
    return M2 / n


# With well-behaved data, both work fine
data_easy = [1.0, 2.0, 3.0, 4.0, 5.0]
print(f"Easy data - Naive:  {naive_variance(data_easy):.10f}")
print(f"Easy data - Stable: {stable_variance(data_easy):.10f}")
print(f"Easy data - NumPy:  {np.var(data_easy):.10f}")

# With data that has a large offset, naive fails
data_hard = [1e9 + 1, 1e9 + 2, 1e9 + 3, 1e9 + 4, 1e9 + 5]
print(f"\nHard data - Naive:  {naive_variance(data_hard):.10f}")
print(f"Hard data - Stable: {stable_variance(data_hard):.10f}")
print(f"Hard data - NumPy:  {np.var(data_hard):.10f}")
print(f"Expected:           2.0000000000")

Why This Matters for AI-Generated Code#

AI coding agents generate mathematically correct but numerically naive code with high confidence. Common patterns to watch for:

AI Might Generate

Problem

Better Alternative

if x == 0.0:

Exact float comparison

if abs(x) < tol:

E[X²] - E[X]²

Catastrophic cancellation

Welford’s algorithm or np.var

(a - b) / (c - d)

Division by near-zero

Check denominator magnitude

sum(small_numbers) + big_number

Loses small numbers

math.fsum() or sum small first

x ** 0.5 for large x

Overflow

math.sqrt(x)

Manual norm: sqrt(sum(xi**2))

Overflow/underflow

np.linalg.norm()

The rule: Never trust AI-generated numerical code without checking for these patterns. The code will run, the tests may pass (if the test data is well-conditioned), but the results may be wrong for real-world inputs.

Relative vs. Absolute Tolerance#

When comparing floating-point numbers, you need to decide what “close enough” means.

  • Absolute tolerance: |a - b| < atol. Good when you know the expected magnitude.

  • Relative tolerance: |a - b| / |b| < rtol. Good when values span many orders of magnitude.

NumPy and pytest use both:

# np.isclose uses both absolute and relative tolerance
# Default: rtol=1e-05, atol=1e-08
# True if: |a - b| <= atol + rtol * |b|

a = 1.0000001
b = 1.0000002
print(f"Close? {np.isclose(a, b)}")

# For very small numbers, absolute tolerance dominates
c = 1e-10
d = 2e-10
print(f"Close? {np.isclose(c, d)}  (default atol=1e-8 swamps the difference)")
print(f"Close? {np.isclose(c, d, atol=0)}  (with atol=0, relative tolerance applies)")
# In pytest, use pytest.approx
import pytest

# These are equivalent:
assert 0.1 + 0.2 == pytest.approx(0.3)
assert 0.1 + 0.2 == pytest.approx(0.3, rel=1e-6)
assert 0.1 + 0.2 == pytest.approx(0.3, abs=1e-12)

print("All assertions passed")

Choosing Tolerances#

How tight should your tolerances be? It depends on what you are computing:

Computation Type

Typical Tolerance

Rationale

Arithmetic identity (a + b - b == a)

1e-15 (near machine epsilon)

Should be exact or nearly so

Numerical integration

1e-8 to 1e-6

Depends on method and step size

Iterative solver (Newton’s method)

1e-10 to 1e-6

Depends on convergence criteria

Monte Carlo simulation

1e-2 to 1e-1

Statistical error dominates

Comparison with experimental data

Depends on measurement uncertainty

Match the experiment’s precision

Never use the default tolerance without thinking about it. The default rtol=1e-5 in np.isclose is reasonable for many cases but too loose for some and too tight for others.

Exercise 1: Find the Numerical Bug (10 min)#

The function below computes the quadratic formula. It works for most inputs but fails for certain values. Find the problematic case, explain why it fails, and fix it.

import math


def quadratic_roots(a, b, c):
    """Solve ax^2 + bx + c = 0 using the quadratic formula."""
    discriminant = b**2 - 4 * a * c
    if discriminant < 0:
        raise ValueError("No real roots")
    sqrt_disc = math.sqrt(discriminant)
    x1 = (-b + sqrt_disc) / (2 * a)
    x2 = (-b - sqrt_disc) / (2 * a)
    return x1, x2


# Works fine for well-separated roots
print(quadratic_roots(1, -3, 2))  # x=1, x=2

# Try this: a = 1, b = -1e8, c = 1
# The exact roots are approximately 1e8 and 1e-8
x1, x2 = quadratic_roots(1, -1e8, 1)
print(f"x1 = {x1}")
print(f"x2 = {x2}")
print(f"x2 should be approximately 1e-8, got {x2}")

# Verify by plugging back in: a*x^2 + b*x + c should be 0
print(f"Residual for x2: {1 * x2**2 + (-1e8) * x2 + 1}")

Hint: The issue is catastrophic cancellation in one of the roots when b and sqrt(discriminant) are nearly equal. The fix uses the identity x1 * x2 = c/a to compute the smaller root from the larger one:

# After computing x1 with the standard formula:
x2 = c / (a * x1)

Section 2: Physical Units and Dimensional Analysis#

In 1999, NASA’s Mars Climate Orbiter was lost because one team used pound-force seconds and another used newton-seconds. The spacecraft approached Mars too closely and disintegrated. Cost: $327 million.

Unit errors are not exotic. They happen in research code constantly. A temperature in Celsius gets passed to a function expecting Kelvin. A pressure in atm gets multiplied by a constant in Pa. An energy in eV gets compared with a value in kJ/mol.

The Problem with Comments#

The traditional approach to units in scientific code is comments:

temperature = 298.15  # Kelvin
pressure = 1.0  # atm
R = 8.314  # J/(mol·K)

# BUG: pressure is in atm but R expects Pa
volume = R * temperature / pressure

Comments do not prevent bugs. The computer does not read comments. A better approach is to encode units in the code itself.

Using pint for Unit-Aware Computation#

pint is a Python library that attaches units to numbers and checks dimensional consistency.

# Install pint if needed: pip install pint
import pint

ureg = pint.UnitRegistry()
Q_ = ureg.Quantity

# Define quantities with units
temperature = 298.15 * ureg.kelvin
pressure = 1.0 * ureg.atm
R = 8.314 * ureg.joule / (ureg.mol * ureg.kelvin)

# pint handles unit conversion automatically
volume = (R * temperature / pressure).to(ureg.liter / ureg.mol)
print(f"Molar volume: {volume:.4f}")
# pint catches dimensional errors
try:
    # Cannot add temperature and pressure
    result = temperature + pressure
except pint.DimensionalityError as e:
    print(f"Caught error: {e}")
# Unit conversion
temp_c = Q_(25, ureg.degC)
temp_k = temp_c.to(ureg.kelvin)
temp_f = temp_c.to(ureg.degF)
print(f"{temp_c} = {temp_k} = {temp_f:.1f}")

# Energy conversion
energy = 1.0 * ureg.eV
print(f"{energy} = {energy.to(ureg.kJ / ureg.mol):.2f}")
print(f"{energy} = {energy.to(ureg.joule):.4e}")

When to Use Units in Code#

pint adds overhead (both in runtime and code verbosity). Here are guidelines:

Always use units for:

  • Functions that accept physical quantities as arguments

  • Code that converts between unit systems

  • Interfaces between different parts of a codebase (where unit assumptions may differ)

Units are optional for:

  • Internal calculations where all units are consistent and documented

  • Performance-critical inner loops (strip units, compute, reattach)

  • Simple scripts where the author and user are the same person

Dimensional Analysis as a Validation Tool#

Even if you do not use pint everywhere, you can use dimensional analysis to check your formulas. If a calculation that should produce a length produces a length² instead, there is a bug. You can do this on paper or with pint:

# Check: does the ideal gas law give volume per mole?
result = R * temperature / pressure
print(result.dimensionality)  # Should be [length]^3 / [substance]

Exercise 2: Catch the Unit Bug (10 min)#

The function below computes the Reynolds number for pipe flow. It has a unit error. Use pint to find and fix it.

def reynolds_number(velocity, diameter, density, viscosity):
    """Compute Reynolds number for pipe flow.

    Parameters
    ----------
    velocity : float
        Flow velocity in m/s
    diameter : float
        Pipe diameter in cm  # <-- note the unit!
    density : float
        Fluid density in kg/m^3
    viscosity : float
        Dynamic viscosity in Pa·s

    Returns
    -------
    float
        Reynolds number (dimensionless)
    """
    # Re = ρvD/μ
    return density * velocity * diameter / viscosity


# Water flowing at 1 m/s through a 5 cm diameter pipe
Re = reynolds_number(
    velocity=1.0,     # m/s
    diameter=5.0,     # cm -- but the formula needs meters!
    density=1000.0,   # kg/m^3
    viscosity=0.001,  # Pa·s
)
print(f"Reynolds number: {Re:.0f}")
print(f"Expected: ~50000, got: {Re:.0f}")
print("Off by a factor of 100 due to cm vs m!")

# TODO: Rewrite this function using pint so that the units are
# handled automatically regardless of what units the caller uses.

Section 3: Validating Against Known Results#

The testing module teaches you to write unit tests: given input X, expect output Y. But for scientific code, the harder question is: how do you know that Y is correct?

Validation Strategies#

1. Analytical Solutions#

If your code solves a general problem, test it on special cases that have closed-form solutions.

  • Numerical integrator → integrate a polynomial (exact answer)

  • ODE solver → solve an exponential decay (exact answer)

  • Optimization → minimize a quadratic (minimum is known)

  • PDE solver → use a manufactured solution

from scipy import integrate

# Test a numerical integrator against an analytical solution
# ∫₀¹ x² dx = 1/3
result, error = integrate.quad(lambda x: x**2, 0, 1)
analytical = 1 / 3

print(f"Numerical: {result}")
print(f"Analytical: {analytical}")
print(f"Error: {abs(result - analytical):.2e}")
assert abs(result - analytical) < 1e-10, "Integration failed!"
from scipy.integrate import solve_ivp

# Test an ODE solver: dy/dt = -k*y, y(0) = 1
# Analytical solution: y(t) = exp(-k*t)
k = 0.5
t_span = (0, 10)
t_eval = np.linspace(0, 10, 100)

sol = solve_ivp(lambda t, y: -k * y, t_span, [1.0], t_eval=t_eval)

analytical = np.exp(-k * t_eval)
max_error = np.max(np.abs(sol.y[0] - analytical))
print(f"Max error: {max_error:.2e}")
assert max_error < 1e-6, f"ODE solver error too large: {max_error}"

2. Conservation Laws#

Many physical simulations should conserve something: energy, mass, momentum, charge. Check that these quantities remain constant (within tolerance).

def test_energy_conservation(simulation_result):
    """Verify total energy is conserved throughout simulation."""
    energies = [step.kinetic + step.potential for step in simulation_result]
    initial_energy = energies[0]
    for i, energy in enumerate(energies):
        assert abs(energy - initial_energy) / abs(initial_energy) < 1e-6, (
            f"Energy not conserved at step {i}: "
            f"{energy} vs initial {initial_energy}"
        )

3. Convergence Testing#

A correct numerical method should improve as you increase resolution (finer grid, more samples, tighter tolerance). If it does not, something is wrong.

# Convergence test: trapezoidal rule should converge as O(h^2)
from scipy.integrate import trapezoid

analytical = 1 / 3  # ∫₀¹ x² dx

print(f"{'N':>8s} {'Error':>12s} {'Ratio':>8s}")
prev_error = None
for n in [10, 20, 40, 80, 160, 320]:
    x = np.linspace(0, 1, n)
    result = trapezoid(x**2, x)
    error = abs(result - analytical)
    ratio = prev_error / error if prev_error else float('nan')
    print(f"{n:>8d} {error:>12.2e} {ratio:>8.2f}")
    prev_error = error

# The ratio should approach 4.0 (since error ~ h^2 and h halves each time)

4. Symmetry and Invariants#

Physical properties often have symmetries you can test:

  • A distance function should be symmetric: d(a, b) == d(b, a)

  • A rotation should preserve vector magnitude

  • An equation of state should reduce to ideal gas at low pressure

  • An interpolation should exactly reproduce data points

These are excellent candidates for property-based testing with Hypothesis:

from hypothesis import given
import hypothesis.strategies as st

@given(
    a=st.floats(min_value=-1e6, max_value=1e6),
    b=st.floats(min_value=-1e6, max_value=1e6),
)
def test_distance_symmetric(a, b):
    assert abs(distance(a, b) - distance(b, a)) < 1e-12

5. Comparison with Published Results#

For domain-specific calculations, compare your results with values from textbooks, NIST databases, or published papers. Store these as regression tests:

def test_water_density_at_25C():
    """Compare with NIST value: 997.05 kg/m³ at 25°C, 1 atm."""
    rho = compute_density(T=298.15, P=101325, species="water")
    assert rho == pytest.approx(997.05, rel=0.01)  # 1% tolerance

Exercise 3: Write Validation Tests (15 min)#

Write tests for the following function using at least three different validation strategies (analytical solution, convergence, symmetry/invariants).

def numerical_derivative(f, x, h=1e-5):
    """Compute the derivative of f at x using central differences."""
    return (f(x + h) - f(x - h)) / (2 * h)


# Test 1: Analytical solution
# f(x) = x^3, f'(x) = 3x^2
# Write a test that verifies this at several points

# Test 2: Convergence
# As h decreases, the error should decrease (until roundoff dominates)
# Write a test that checks the error decreases for h = 1e-2, 1e-4, 1e-6

# Test 3: Symmetry/invariant
# The derivative of a constant function should be zero
# The derivative of a linear function should be the slope

# Your tests here:

Section 4: Reproducibility#

A scientific computation is only useful if someone else can reproduce it. This means the same code, with the same data and parameters, should produce the same results on a different machine.

Random Seeds#

Any computation involving randomness (Monte Carlo, stochastic optimization, random sampling) must set and record seeds for reproducibility.

# Bad: different result every time
print("Without seed:", np.random.normal(0, 1, 3))
print("Without seed:", np.random.normal(0, 1, 3))

# Good: reproducible
rng = np.random.default_rng(seed=42)
print("\nWith seed:", rng.normal(0, 1, 3))

rng = np.random.default_rng(seed=42)
print("With seed:", rng.normal(0, 1, 3))  # Same result

Best practices for random seeds:

  • Use np.random.default_rng(seed=N) (new-style) instead of np.random.seed(N) (legacy)

  • Pass the rng object explicitly rather than relying on global state

  • Record the seed in your output/logs

  • In tests, always set a seed so tests are deterministic

Environment Pinning#

Your results depend on the exact versions of NumPy, SciPy, and other libraries. Different versions may use different algorithms or default parameters.

# Record your exact environment
pip freeze > requirements-frozen.txt

# Or with uv
uv pip compile pyproject.toml -o requirements-frozen.txt

# Even better: use uv.lock
uv lock

Always commit your lock file to version control. When someone clones your repo in 2028, they need to know which versions you used in 2026.

Recording Provenance#

For important results, record what produced them:

import json
import subprocess

provenance = {
    "git_commit": subprocess.check_output(
        ["git", "rev-parse", "HEAD"]
    ).decode().strip(),
    "python_version": sys.version,
    "numpy_version": np.__version__,
    "parameters": {"temperature": 298.15, "pressure": 101325},
    "random_seed": 42,
}

# Save alongside your results
with open("results_provenance.json", "w") as f:
    json.dump(provenance, f, indent=2)

Tips and Tricks#

  • Use math.fsum() instead of sum() for floating-point sums. It tracks partial sums to avoid accumulation of rounding errors.

  • Never compare floats with ==. Use np.isclose(), pytest.approx(), or explicit tolerance checks.

  • When AI generates numerical code, ask it about numerical stability. Prompt: “Are there inputs where this formula is numerically unstable?”

  • Use np.float64 (the default) for scientific computing. Only use float32 when you specifically need it (GPU computation, memory constraints) and understand the precision tradeoff.

  • Test with extreme values. If your code works for x=1.0, try x=1e-15, x=1e15, and x=0.0.

  • Use pint at the boundaries of your code (function inputs/outputs) even if you strip units for internal computation.

  • Always set random seeds in tests. Flaky tests that depend on random numbers waste everyone’s time.

  • Include a convergence test for any numerical method. If the answer does not improve with resolution, the implementation is wrong.

  • Compare with scipy and numpy implementations before writing your own numerical code. They handle edge cases you have not thought of.

Foundational Concepts to Commit to Memory#

  • Floating-point numbers are approximations. 0.1 + 0.2 != 0.3 because 0.1 cannot be represented exactly in binary. This is not a bug — it is how computers work.

  • Catastrophic cancellation occurs when subtracting nearly equal numbers, amplifying rounding errors. Watch for AI-generated code that uses mathematically correct but numerically unstable formulas.

  • Choose tolerances deliberately. The default rtol=1e-5 is not always appropriate. Think about what precision your computation can actually achieve.

  • Physical units in code prevent an entire class of bugs. Use pint to encode units explicitly, especially at function boundaries.

  • Validate scientific code against analytical solutions, conservation laws, convergence tests, and published results. Unit tests alone are not sufficient — you need to verify that the science is correct, not just that the code runs.

  • Set and record random seeds for any stochastic computation. Use np.random.default_rng(seed=N) instead of the legacy np.random.seed().

  • Pin your environment with lock files and record computational provenance (git commit, library versions, parameters) alongside results.

Knowing vs. Doing: Reflection#

General software engineering teaches you that tests verify behavior: given input X, you expect output Y. Scientific software engineering adds a harder requirement: you also need to verify that Y is physically correct.

A web application that rounds a price from \(19.999 to \)20.00 is fine. A simulation that rounds an energy from -0.001 eV to 0.000 eV just changed an exothermic reaction to thermoneutral. The code is correct. The science is wrong.

AI coding agents make this worse because they generate plausible numerical code with high confidence. The quadratic formula, the variance formula, the numerical derivative — an AI will write each of these using the textbook formula, and the textbook formula is often numerically naive. The AI has no concept of machine epsilon, catastrophic cancellation, or numerical stability. It does not know that your data might have values near 1e15 or 1e-15.

The defense is not to avoid AI. It is to know where AI-generated code is most likely to be wrong and to have validation strategies ready. Analytical solutions, convergence tests, conservation laws, dimensional analysis, and comparison with published results — these are the tools that catch the bugs that unit tests miss. Use them.

Additional Resources#