Thermodynamic equilibrium is not a motionless state. Molecules continue to move, collide, and exchange energy. Equilibrium means that the probability distributions of macroscopic observables are stationary and that no sustained macroscopic flow is driven by a remaining imbalance inside the stated system boundary.
The historical phrase "heat death" describes an idealized limit in which usable macroscopic gradients have disappeared. It does not mean that all energy, microscopic motion, or fluctuations vanish.
Thermal equilibrium requires no net heat transfer between parts that can exchange energy. Their temperatures are equal. Mechanical equilibrium requires no unbalanced pressure or generalized force that can drive macroscopic motion. Diffusive or chemical equilibrium requires no net particle transfer or reaction driven by unequal chemical potentials.
For two subsystems able to exchange energy, volume, and particles, the equilibrium conditions can be expressed schematically as
\[T_A=T_B,\qquad P_A=P_B,\qquad\mu_A=\mu_B\]Here \(T\) is temperature, \(P\) is pressure, and \(\mu\) is chemical potential. Only the conditions associated with exchanges permitted by the boundary apply. An insulating rigid wall, for example, prevents heat and volume exchange, so unequal temperatures or pressures can persist without the wall moving or conducting.
Equilibrium is therefore defined relative to a system, constraints, and observation scale. A gas may look uniform in large spatial cells while finer measurements still show a temperature gradient.
For an isolated composite system, equilibrium is the macrostate that maximizes total entropy subject to conserved energy, volume, particle number, and other constraints. The second law states
\[\Delta S_{\mathrm{isolated}}\ge0\]The inequality describes spontaneous macroscopic change. At stable equilibrium, no allowed small exchange can increase the total entropy further.
The temperature condition follows directly. Let subsystem \(A\) gain a small energy \(dU_A\) while subsystem \(B\) loses the same amount. Then
\[dS_{\mathrm{total}} =dU_A\left(\frac{1}{T_A}-\frac{1}{T_B}\right)\]Energy flows spontaneously in the direction that increases total entropy. If \(T_B>T_A\), transfer from \(B\) to \(A\) makes the expression positive. At the entropy maximum, the coefficient of the allowed exchange vanishes, giving equal temperatures.
The same reasoning with volume or particle exchange gives equal pressure or chemical potential under the appropriate constraints.
At equilibrium, an instantaneous pressure, particle count in a region, or molecular kinetic energy still fluctuates. What becomes stable is the probability distribution and its macroscopic averages, not each microscopic event.
Detailed balance is one equilibrium criterion for a Markov description. At equilibrium, the probability flow from state \(i\) to state \(j\) is balanced by the reverse flow:
\[p_iW_{i\to j}=p_jW_{j\to i}\]Here \(p_i\) is the equilibrium probability and \(W_{i\to j}\) is a transition rate. Individual transitions continue, but their probability currents cancel pairwise. Some equilibrium descriptions do not require this particular Markov representation, so detailed balance is a sufficient modeling structure rather than the definition of all equilibrium physics.
A driven steady state can have time-independent averages while energy or matter flows continuously. A metal bar held between hot and cold reservoirs can develop a stable temperature profile, yet heat keeps crossing it. A pipe can maintain steady density and speed while mass enters one end and leaves the other.
For heat crossing area \(A\) during time \(\Delta t\), an average heat flux is
\[J_Q=\frac{\Delta Q}{A\,\Delta t}\]A nonzero sustained flux reveals a nonequilibrium steady state even when temperatures at each measured point no longer drift. This is why an equilibrium test needs boundary and flux records, not only snapshots.
A metastable state is locally persistent but not the global equilibrium state. A supercooled liquid, a supersaturated vapor, or a system trapped behind a large energy barrier can show stable observables for a long time before a rare fluctuation triggers a transition.
Observation time matters. If the relaxation time exceeds the data window, "no detected change" is weaker than "equilibrium." Hidden conserved quantities, glassy dynamics, poor mixing, and finite-size barriers can all extend relaxation. A responsible classification allows an undetermined result and reports the range of observed time scales.
Energy is conserved, but not all energy is equally available for producing work. A heat engine needs reservoirs at different temperatures. Its maximum reversible efficiency is
\[\eta_{\mathrm{Carnot}}=1-\frac{T_C}{T_H}\]When the cold and hot reservoir temperatures become equal, the ideal efficiency becomes zero. Thermal energy remains, but there is no temperature difference for the engine to exploit.
For a system held at fixed temperature and volume by a reservoir, the Helmholtz free energy is
\[F=U-TS\]At those fixed external conditions, spontaneous change lowers \(F\) until equilibrium is reached. At fixed temperature and pressure, the corresponding potential is the Gibbs free energy \(G=H-TS\), where \(H\) is enthalpy. These criteria are more specific than saying that entropy always rises inside whatever subsystem happens to be displayed.
In the heat-death idealization, large-scale gradients and accessible free-energy differences have been exhausted. Microscopic energy and equilibrium fluctuations remain. Local structure can also form in an open subsystem while entropy production elsewhere more than compensates.
Applying the phrase "heat death of the universe" is a cosmological extrapolation, not a result established by a box of gas. Gravity is long-ranged, spacetime expands, black holes carry entropy, and the future depends on cosmological parameters and on physics that may not yet be known.
Ordinary thermodynamics supports the limited statement that isolated systems tend toward macrostates with fewer exploitable gradients. It does not by itself determine the final state, lifetime, geometry, or temperature history of the universe. The small-system model is valuable for understanding equilibrium, but it should not be presented as a complete cosmological prediction.
Choose observables connected to possible imbalances: temperature by region, pressure on opposite walls, density, chemical composition, center-of-mass motion, and energy or particle flux. Preserve raw traces as well as averages.
import numpy as np
# Two equal heat capacities, isolated except for exchange with each other.
capacity, conductance = 100.0, 2.0
times = np.linspace(0, 200, 1001)
mean_temperature = 300.0
difference = 40 * np.exp(-2 * conductance * times / capacity)
first, second = mean_temperature + difference / 2, mean_temperature - difference / 2
flux = conductance * (first - second)
assert np.allclose(capacity * (first + second), 2 * capacity * mean_temperature)
print("Final temperature difference (K):", difference[-1])
print("Final heat flow (W):", flux[-1])
Thresholds should come from measurement uncertainty and expected finite-system fluctuations, not from a convenient number chosen after seeing the data. Recording more closely spaced correlated samples does not automatically strengthen the evidence.
An equilibrium claim is strongest when several observables are stationary, permitted net fluxes vanish within uncertainty, independent initial conditions approach the same distribution, and the conclusion survives reasonable changes in time window and spatial resolution. Even then, the statement remains tied to the declared model, constraints, and observation duration.
Two bodies with equal heat capacities exchange heat while isolated from the outside. The question for this calculation is precise: how does temperature difference change when we change elapsed time, while keeping the other choices fixed? The earlier sections explain the physical relationship. Here we turn one part of that relationship into a calculation that you can run, inspect, and change in Google Colab.
A declining temperature difference is evidence of equilibration in this model, not a claim about the whole universe. Keep that sentence beside the results. A formula can return a number outside its useful range, and a plotting library will usually draw that number without asking whether the physical assumptions still hold. The selected interval is from 0 to 200 s. It gives us a specific domain to discuss instead of leaving the graph's range to a software default.
Use the notebook link above the lesson, run the setup cell, and then run the cells in order. The code below is also included there. NumPy handles the arrays of numerical values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these libraries or notebook cells are unfamiliar, start with Your first physics notebook.
In this small example, q stands for elapsed time, expressed in s. The output is
temperature difference, expressed in K. The equation below uses the numerical values in those
units. Any fixed coefficients therefore carry the units needed to make the relation
consistent. A value supplied in another unit must be converted before it enters this
expression.
This is a function of one changing input. It is not a statement that the physical system has only one variable. We deliberately hold the other inputs fixed so that one cause of variation is visible. Changing several inputs at once would make it harder to tell which change produced the output difference. Write down the held-fixed choices before trying a different experiment.
At 50 s, the expression gives 5.41341 K. This is our reference calculation. It is a prediction of the stated example, not a new measurement. Its displayed digits help us compare implementations. They should not be read as a claim that physical inputs are known to six significant figures.
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
q = sp.Symbol("q", real=True)
expression = sp.sympify("40*exp(-0.04*q)", locals={"q": q})
reference_input = 50.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "s")
print("Predicted temperature difference:", reference_output, "K")
sp.Symbol declares a mathematical symbol. It does not assign a numerical measurement
to that symbol. subs then replaces the symbol with our chosen input, and float
converts the resulting symbolic number into a standard Python numerical value.
Keeping these steps separate lets us inspect the equation before numerical substitution.
It also prevents a later plot from becoming the only surviving record of the model.
Before drawing hundreds of points, calculate three. The lower endpoint gives 40 K. The midpoint, at 100 s, gives 0.732626 K. The upper endpoint gives 0.0134185 K. Read these together with the assumptions: they describe different choices of elapsed time within the same example, with the other inputs held fixed.
These three values are a useful first check, but they do not establish the shape between them. Two endpoints can be equal even when the curve bends or oscillates in between. Likewise, a large change between endpoints does not tell us whether the relationship is linear. We need the equation and intermediate samples to answer those questions.
evaluate = sp.lambdify(q, expression, modules="numpy")
inputs = np.array([0.0, 100.0, 200.0])
outputs = np.asarray(evaluate(inputs), dtype=float)
outputs = np.broadcast_to(outputs, inputs.shape)
for input_value, output_value in zip(inputs, outputs):
print(f"{input_value:.6g} s -> {output_value:.6g} K")
assert np.all(np.isfinite(outputs))
lambdify turns the symbolic expression into a numerical function. We explicitly select
NumPy as its numerical backend so it can accept an array. The same expression now has
two useful forms: one for algebra and one for calculating many cases. The assertion
checks that the chosen inputs produce finite outputs. It would catch an infinity or an
undefined numerical result, but a finite value can still be physically inappropriate.
The horizontal axis shows elapsed time; the vertical axis shows temperature difference. Every plotted point is a prediction of the same expression. We mark the reference case separately so that a reader can connect the earlier printed value to its place on the curve. The axis labels include units because a shape without a scale cannot tell us the size of a physical effect.
input_grid = np.linspace(0.0, 200.0, 301)
output_grid = np.asarray(evaluate(input_grid), dtype=float)
output_grid = np.broadcast_to(output_grid, input_grid.shape)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(input_grid, output_grid, label="Stated model")
ax.scatter([reference_input], [reference_output], label="Reference case", zorder=3)
ax.set_xlabel("Elapsed time (s)")
ax.set_ylabel("Temperature difference (K)")
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()
Look for a sign change, a turning point, or a region where the curve becomes steep. Connect each feature to the expression rather than to the colour of the line. If the curve has a minimum or maximum, changing the input in opposite directions may have similar effects on the output near that point. If it is nearly straight over a short interval, a local linear approximation may be useful even when the complete expression is nonlinear.
Increasing the number of samples makes the line smoother and may reveal features that a coarse grid missed. It does not improve the physical inputs or enlarge the model's validity range. For quantities that can take only discrete values, use the line as a guide to the relationship and interpret only the allowed input values. A plotting function does not enforce such restrictions for you.
A derivative asks a more specific question than the whole graph: how quickly does temperature difference change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 50 s is -0.216536 in those ratio units. Locally, the output decreases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.
\[f'(q) = - 1.6 e^{- 0.04 q}\]For a small input change, multiply the derivative by that change to estimate the output change. Then compare that estimate with a fresh evaluation of the full expression. The distinction between these two calculations matters: the derivative gives a tangent approximation, while substitution evaluates the chosen expression at the new point.
slope_expression = sp.diff(expression, q)
slope_at_reference = float(slope_expression.subs(q, reference_input))
changed_input = 51.0
linear_prediction = reference_output + slope_at_reference * (
changed_input - reference_input
)
full_prediction = float(evaluate(changed_input))
print("Symbolic derivative:", slope_expression)
print("Tangent prediction:", linear_prediction, "K")
print("Full expression:", full_prediction, "K")
print("Approximation difference:", full_prediction - linear_prediction, "K")
Here the changed input is 51 s. The tangent estimate is 5.19687 K, while the full expression gives 5.20115 K. If the two values are close, it means the chosen input change is small enough for this local approximation at this point. It does not mean the entire model is linear. If the slope is zero, a quadratic or higher-order term may supply the leading change instead.
This is also the beginning of uncertainty propagation. If the input has a small stated standard uncertainty, the magnitude of the slope times that uncertainty estimates one contribution to output uncertainty. Do not automatically use the same rule for a wide interval, a discontinuity, a turning point with zero first derivative, or several correlated uncertain inputs. Those situations need more of the model than one slope.
We can estimate the same slope from values on either side of the reference point. Subtract the lower output from the upper output and divide by twice the input step. Parentheses are essential: the entire output difference must be divided by the entire input interval. Without them, Python can execute a different mathematical expression while still producing a plausible number.
The calculation below uses three decreasing step sizes. Each estimate is compared with the symbolic derivative, so the reference is independent of the numerical difference formula. Near an endpoint, it is acceptable here to evaluate a small extension only because the displayed mathematical expression is smooth there; such a check does not assert that extrapolated values describe additional physical cases.
input_span = 200.0
for fraction in [1e-2, 1e-3, 1e-4]:
step = input_span * fraction
upper = float(evaluate(reference_input + step))
lower = float(evaluate(reference_input - step))
numerical_slope = (upper - lower) / (2 * step)
difference = numerical_slope - slope_at_reference
print(f"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}")
For a smooth function, reducing the step often reduces the approximation error at first. Very small steps can eventually make subtraction of nearly equal floating-point values less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare the observed behaviour over a useful range of steps instead of choosing the smallest number the computer can represent.
An absolute slope difference is useful when the expected slope is near zero. A relative difference would divide by a very small reference and could look enormous even when the absolute discrepancy is tiny. Away from zero, a relative difference can help compare quantities with very different scales. The tolerance should reflect the question and the numerical method, rather than a universal decimal threshold copied into every test.
Make one copy of the reference calculation before editing it. Choose a second value of elapsed time inside the stated interval, predict whether temperature difference will rise or fall, and then evaluate the expression. Place the prediction and the result in a text cell. If they disagree, identify whether the mistake was in the sign, the unit conversion, the algebra, or the assumption about how the curve behaves.
Next choose a shorter plotting interval around the reference point. Compare the local curve with its tangent approximation. Then widen the interval again. The difference shows why a useful local estimate need not describe the whole range. Keep the axis labels and numerical scale visible when comparing the plots; automatic axis limits can make two different effects appear equally large.
Finally, return to the physical limit stated at the start: A declining temperature difference is evidence of equilibration in this model, not a claim about the whole universe. Describe one change to the setup that would violate that limit. State what new input, equation, or observation would be needed before trusting an answer in the changed situation. This last step connects the Python experiment to the physics instead of treating successful execution as the only criterion for a useful result.
Before saving, restart the runtime and run all cells in order. A result that depends on an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep unrounded values for later calculations, round only the reported output, and label any new data as measured, assumed, or generated. The graph and printed values should remain traceable to the same expression and the same choices of inputs.
There is another way to check that the expression and its derivative describe the same relationship. Add up the small output changes predicted by the slope across the chosen input interval. In the continuous limit, this integral equals the output at the upper endpoint minus the output at the lower endpoint. The result has units of K: the input unit in the integration cancels the input unit in the denominator of the slope.
This statement is about the mathematics of this particular relationship. It does not assign a new physical meaning to an arbitrary area under a graph. For example, an area under force versus distance represents work, while an area under a different pair of quantities may represent something else or have no standard name. Always carry the axis units through the calculation before naming an integral.
slope_function = sp.lambdify(q, slope_expression, modules="numpy")
endpoint_change = float(evaluate(200.0) - evaluate(0.0))
for points in [101, 201, 401]:
grid = np.linspace(0.0, 200.0, points)
slopes = np.asarray(slope_function(grid), dtype=float)
slopes = np.broadcast_to(slopes, grid.shape)
integrated_change = np.trapezoid(slopes, grid)
print(
points,
"integrated change:",
integrated_change,
"endpoint change:",
endpoint_change,
)
The trapezoidal rule joins neighbouring slope samples with straight segments and adds their signed areas. A negative contribution remains negative; replacing every slope by its magnitude would calculate a different quantity. Increasing the sample count provides a practical refinement check. If the values do not settle toward the endpoint difference, first inspect the interval, singularities, and array ordering.
Do not conclude that two agreeing calculations prove the model is physically complete. Both use the same selected relationship, so an omitted effect would be omitted from both. Their agreement is evidence that the numerical tools implement that relationship consistently. Comparing with an independent experiment or a more appropriate physical model is a separate test.
Keep this comparison in the notebook when you change the expression. It is particularly useful after adding a coefficient, changing a sign convention, or converting an input unit. A code cell that produces a smooth graph can conceal these mistakes; a second calculation of the same output change gives you another place to notice them.