A Byte of PhysicsLogo

Energy accounting in code

Energy accounting is a debugging tool. Every update should explain whether energy stayed in modeled stores, crossed a boundary, or changed through a declared source, sink, or numerical residual. “Energy decreased” is not a result until the system boundary and every transfer sign are defined.

Think like a programmer

Return diagnostics with every state transition: timestamp, previous named stores, signed transfers into the system, next named stores, residual, tolerance policy, and component/boundary attribution. Keep this in framework-free model code so CI can test it. Use the same sign convention everywhere: transfer into the selected system is positive, transfer out is negative. Do not make the UI infer conservation from an animated trace.

Model checklist

Inputs
Selected system boundary, previous named energy stores, signed work/heat/field/boundary/thermostat transfers, next stores, timestamp/interval, absolute and relative tolerance policy, and expected numerical order.
State
Per-step ledger entries, total previous/next energy, expected next energy, residual, cumulative residual, and transfer categories.
Rule
Sum stores on each side of the interval; add declared signed transfers to previous total; subtract that expectation from actual next total; accumulate and classify residual.
Output
Pass/warning/fail ledger diagnostic, residual history, category attribution, and reproducible tolerance context.
Check
Closed ideal case keeps residual within a scale-aware tolerance; a declared negative transfer reduces expected system energy; reversing system boundary reverses transfer sign but preserves physical interpretation; cumulative residual is tracked rather than hidden by per-step rounding; intentionally dissipative models pass only when loss is a named transfer.
\[r=E_{\rm next}-\left(E_{\rm previous}+Q-W\right)\]

For a system with prior total Eprevious, signed transfers Tinto, and actual next total Enext, the residual is:

\[r=E_{next}-(E_{previous}+T_{into}),\qquad |r|\le \varepsilon_{abs}+\varepsilon_{rel}\max(|E_{previous}|,|E_{next}|)\]

A useful record is structured data, not a console sentence: { timeStart, timeEnd, storesBefore, storesAfter, transfers: { boundary, drive, damping, thermostat }, residual, tolerance, integrator, step }. This lets a failed test identify which model category changed. Track both per-step and cumulative residual. A tiny systematic error per step can become a large energy drift over a long run.

Choose tolerance from the problem scale and expected method behavior. An absolute-only tolerance fails when the model is rescaled; a relative-only tolerance becomes meaningless near zero energy. Test a simple closed analytic fixture, then a controlled transfer fixture—such as constant work input or known damping loss—before declaring a complex simulation conserved.

Try this experiment

Prediction: A residual reveals an unrecorded transfer or integrator error, while named damping loss can make a decreasing mechanical store fully accounted for.

Design one structured ledger record for a time step. Run a closed ideal fixture and inspect per-step plus cumulative residual. Add a known external work input and verify its transfer sign. Then add damping as a negative system transfer and show why the mechanical-energy decrease is not numerical error. Scale all energies and compare a scale-aware tolerance with an absolute-only rule.

Where this model breaks

Some models intentionally dissipate energy. Their loss must be a named ledger entry; a small residual alone does not prove physical correctness. Missing potential terms, inconsistent time levels, hidden constraints, open boundaries, stochastic thermostats, discretized field energy, and inaccurate work quadrature can all make a ledger incomplete even when arithmetic is correct.

Summary

Return signed, structured energy diagnostics with state updates. Track per-step and cumulative residuals, state the system boundary and tolerance policy, and distinguish declared physical transfer from numerical error.

Glossary

Self-check

  1. Which values should a transition return?
  2. How does a closed ideal test behave?
  3. Why name dissipation explicitly?
  4. Why track cumulative residual in addition to each step?

Sources

Model contract

Treat the lesson as a small function before treating it as a fact to memorize. Give every value a unit, keep only the state needed for the next step, and make the output easy to inspect.

\[\text{observable output} = f(\text{inputs},\,\text{state})\]
Inputs
Quantities you set or measure, with units and useful bounds.
State
Values the program must retain to reproduce the next result.
Rule
The relationship or update that turns inputs and state into a result.
Check
A known limit, unit check, invariant, or measured result that can expose a bad model.

Implement the idea as a model

For Energy Accounting in Code, write down the quantities you can control, the values your program must retain, and the result a reader could inspect. In Temperature and the First Law, the useful program is not the drawing: it is the smallest explicit model that makes a prediction you can test.

Guided experiment

Prediction: changing one declared input while holding the others fixed should change only the outputs that the model connects to that input. Choose one input, predict the direction of change, then check a limiting case such as zero, a symmetric arrangement, or a familiar low-speed or small-change approximation.

Where this model breaks

This lesson is a teaching model, not a complete simulator. Before using it outside the stated question, check which interactions, scales, uncertainties, boundary conditions, and measurement limits it leaves out.

Summary

Treat Energy Accounting in Code as a contract: named inputs and units enter a rule, the rule produces an observable result, and a known limit or invariant checks whether the implementation deserves trust.

Glossary

  • Input: a measured value or chosen parameter supplied to a model.
  • State: the smallest set of values needed to continue or reproduce a model.
  • Validation: comparing an output with a known result, limit, invariant, or measurement.

Self-check

  1. Which values are inputs, and which values must remain state?
  2. What observable result would tell you the model is behaving as expected?
  3. Which assumption would you test first before applying the model to a real system?

Model review: turn Energy Accounting in Code into a test

Return conservation diagnostics from state updates and distinguish modeled transfer from numerical residual.

  1. Name the inputs and units that the temperature and the first law model needs.
  2. Separate the state you must keep from values you can calculate when needed.
  3. Write one rule that maps the current state and inputs to an observable result.
  4. Choose a limiting case, unit check, invariant, or known result before trusting an output.
  5. State one assumption you would change before using this simplified model for a real decision.

Share to: