Writing code that runs is not enough — it must produce correct results. Debugging and validation are essential skills for computational physicists.
Common bug categories
| Bug type | Example | Fix |
|---|---|---|
| Syntax | Missing colon after if | Read the error message |
| Runtime | Division by zero | Add a guard: if x != 0 |
| Logic | Off-by-one in loop bounds | Trace with a small example |
| Numerical | Floating-point drift | Use higher precision or smaller |
Debugging strategies
# 1. Print intermediate values
print(f"Step {i}: x={x:.6f}, v={v:.6f}")
# 2. Use assertions to catch invariants
assert energy > 0, f"Energy went negative at step {i}"
# 3. Test with known inputs
assert abs(kinetic_energy(2.0, 3.0) - 9.0) < 1e-10
Validation hierarchy
- Unit tests — Does each function return the correct output for known inputs?
- Conservation laws — Does total energy / momentum stay constant (within numerical tolerance)?
- Convergence tests — Does halving improve the answer?
- Comparison — Does the code reproduce published results or analytical solutions?
Key insight: The hardest bugs are silent — the code runs without errors but gives wrong results. Conservation-law checks are your best defence: if energy isn't conserved, something is wrong.
Common pitfall: Fixing the symptom where the crash occurred often leaves the cause upstream untouched. Trace the bad value back to where it was born — the crash site is usually just the victim.