Courses / Physics I
Computer Science

Debugging and validation

Physics I 250 words Free to read

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 typeExampleFix
SyntaxMissing colon after ifRead the error message
RuntimeDivision by zeroAdd a guard: if x != 0
LogicOff-by-one in loop boundsTrace with a small example
NumericalFloating-point driftUse higher precision or smaller hh

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

  1. Unit tests — Does each function return the correct output for known inputs?
  2. Conservation laws — Does total energy / momentum stay constant (within numerical tolerance)?
  3. Convergence tests — Does halving hh improve the answer?
  4. 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.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

15practice questions
2interactive scenes
Start Physics I free

Computer Science