Building current in an inductor requires energy. The source must work against the self-induced voltage while the magnetic field grows. In an ideal lossless inductor, that work is stored in the magnetic field and can later be returned to the circuit. In a real device, some energy also becomes internal energy through winding resistance, eddy currents, and magnetic hysteresis.
The lumped formula \(U=LI^2/2\) and the field formula for magnetic energy density describe the same energy at different levels. One uses a circuit state; the other describes where energy is distributed in space.
Under the passive sign convention, an ideal constant inductor obeys
\[V_L=L\frac{dI}{dt}\]The instantaneous electrical power absorbed by the inductor is
\[P=V_LI=LI\frac{dI}{dt}\]Energy supplied while current rises from zero to \(I\) is
\[U_L=\int_0^tP\,dt =\int_0^I LI'\,dI' =\frac{1}{2}LI^2\]The integration variable \(I'\) distinguishes the current during buildup from the final current. The result is nonnegative for positive inductance and is unchanged when current reverses because it depends on current squared.
Differentiating the energy returns the power law:
\[\frac{dU_L}{dt} =LI\frac{dI}{dt} =V_LI\]When this signed power is positive, stored magnetic energy increases. When it is negative, the inductor returns energy to the rest of the circuit.
Because \(1\ \mathrm H=1\ \mathrm{V\,s/A}\),
\[\mathrm H\,\mathrm A^2 =\mathrm{V\,A\,s} =\mathrm J\]Doubling inductance at fixed current doubles stored energy. Doubling current at fixed inductance multiplies energy by four. Constant current means \(dI/dt=0\), so an ideal inductor has zero terminal voltage and constant stored energy—not necessarily zero energy.
For an ideal \(L=2.0\ \mathrm H\) carrying \(I=3.0\ \mathrm A\),
\[U_L=\frac{1}{2}(2.0\ \ \mathrm H)(3.0\ \mathrm A)^2 =9.0\ \mathrm J\]Reversing current to negative three amperes leaves the energy at nine joules. Increasing the current magnitude to six amperes raises it to thirty-six joules, four times the original amount.
For a linear magnetic medium, the magnetic energy density is
\[u_B=\frac{B^2}{2\mu}\]In vacuum, \(\mu=\mu_0\), so
\[u_B=\frac{B^2}{2\mu_0}\]Energy density has units of joules per cubic metre. The total field energy is obtained by integrating over space:
\[U_B=\int_{\mathrm{all\ space}}u_B\,dV\]The phrase “all space” matters. An idealized field may extend outside a component even when an introductory derivation treats the exterior contribution as negligible. A finite solenoid, for example, has fringing fields beyond its winding.
For a general linear material, magnetic energy density can also be written
\[u_B=\frac{1}{2}\mathbf B\cdot\mathbf H\]This simple form assumes a linear, reversible response. Hysteretic materials require a path-dependent treatment, and part of the input energy can be dissipated each cycle.
An ideal long solenoid of length \(\ell\), area \(A\), and turn density \(n\) has approximately
\[B=\mu nI\]Its field-filled volume is approximately \(A\ell\). Integrating the uniform energy density over that volume gives
\[U_B =\frac{B^2}{2\mu}A\ell =\frac{1}{2}\mu n^2A\ell I^2\]Since \(N=n\ell\), the ideal solenoid inductance is
\[L=\mu n^2A\ell =\mu\frac{N^2A}{\ell}\]Substitution recovers \(U_B=LI^2/2\). This agreement shows that the circuit formula is a compact representation of distributed field energy under the solenoid approximation.
For a series source, resistor, and ideal inductor,
\[V_s=IR+L\frac{dI}{dt}\]Multiply by current:
\[V_sI=I^2R+LI\frac{dI}{dt}\]The left side is source power delivered under the corresponding sign convention. The first right-side term is resistor dissipation, and the second is the rate of increase of magnetic energy. Integrating over time gives
\[E_{\mathrm{source}} =E_{\mathrm{resistor}}+\Delta U_L\]During source-free decay through a resistor, magnetic energy decreases while resistor heating increases. Ideally, all initially stored energy becomes internal energy in the resistor:
\[\int_0^\infty I^2R\,dt =\frac{1}{2}LI(0)^2\]For two linearly coupled coils with self-inductances \(L_1\) and \(L_2\), mutual inductance \(M\), and compatible orientation, the stored energy can be written
\[U=\frac{1}{2}L_1I_1^2 +\frac{1}{2}L_2I_2^2 \pm MI_1I_2\]The sign depends on the winding and current reference conventions. Physical passivity requires
\[M^2\le L_1L_2\]Otherwise the quadratic energy expression could become negative for some currents. With \(M=k\sqrt{L_1L_2}\), this condition corresponds to coupling magnitude no greater than one.
When flux linkage \(\lambda\) is nonlinear, the constant-inductance expression is incomplete. Electrical input energy along a reversible path is
\[U=\int_0^I I'\frac{d\lambda}{dI'}\,dI'\]For \(\lambda=LI\), this reduces to the familiar quadratic result. With hysteresis, the magnetic state depends on history, and the area of a hysteresis loop represents energy dissipated per cycle per volume under the appropriate variables. One scalar current is then insufficient to describe the material state.
It can sound puzzling that a magnetic force on a point charge does no work while a magnetic field stores energy. The statements describe different parts of the system. The magnetic part of the Lorentz force is perpendicular to an individual carrier's velocity, but an electric field inside the winding does work on charges as the source establishes the current. Electromagnetic energy then occupies the field configuration around and inside the coil. When current falls, the induced electric field can transfer that energy back to charges in the circuit.
The lumped circuit picture records this process through terminal voltage, current, and the scalar state energy. A field description tracks energy density throughout space and energy flow across a chosen boundary. These accounts must agree when they describe the same boundary and include all relevant fields. Apparent disagreement often comes from counting only the idealized solenoid interior, omitting fringing fields, or treating resistive heating as if energy vanished.
The system boundary therefore belongs in every energy statement. If the boundary encloses only the ideal inductor, positive terminal power raises stored field energy. If it also encloses winding resistance, part of the incoming power raises internal energy. If it encloses the source and the entire circuit, internal transfers cancel and only energy crossing the outer boundary changes the total. A correct formula can still produce an incorrect ledger when its terms refer to different boundaries.
This distinction also explains why unplugging an energized coil is not equivalent to setting its energy to zero. The existing field must collapse through some physical route. It can drive current through a resistor or protection diode, charge parasitic capacitance, create a large voltage and arc, radiate a small amount of energy, or divide among several of these processes. The ideal model predicts the available stored energy; the real circuit determines where that energy goes and how quickly.
import numpy as np
R, L, supply, time = 10.0, 0.1, 5.0, 0.01
current = supply / R * (1 - np.exp(-R * time / L))
inductor_voltage = supply - R * current
stored = 0.5 * L * current**2
source_power = -supply * current
resistor_power = R * current**2
inductor_power = inductor_voltage * current
assert np.isclose(source_power + resistor_power + inductor_power, 0.0)
print("Stored energy (J):", stored)
All branch powers must use the same passive-sign convention; a delivering source then has negative signed power. For sampled data, integrate power with a declared quadrature rule and compare with energy change at matching times.
Zero current gives zero energy in the ideal linear model. Reversing current leaves single-inductor energy unchanged. Doubling current quadruples it. A constant current has zero ideal terminal voltage and constant, not necessarily zero, stored energy. For a lossless calculation, integrated inductor power must equal the change in stored energy.
Real inductors include winding resistance, leakage flux, core saturation, hysteresis, eddy currents, parasitic capacitance, radiation, and temperature dependence. At high frequency, energy is distributed through electric and magnetic fields and can flow through space; a single value of \(L\) may no longer describe the device. Separate physical losses from numerical energy drift by refining the time step and checking an analytic reference.
Store magnetic energy in a linear inductor of inductance 0.1 henry. The question for this calculation is precise: how does magnetic stored energy change when we change inductor current, 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.
Core saturation and hysteresis require a different energy relation. 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 -2 to 2 A. 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 inductor current, expressed in A. The output is
magnetic stored energy, expressed in J. 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 1 A, the expression gives 0.05 J. 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("0.1*q**2/2", locals={"q": q})
reference_input = 1.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "A")
print("Predicted magnetic stored energy:", reference_output, "J")
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 0.2 J. The midpoint, at 0 A, gives 0 J. The upper endpoint gives 0.2 J. Read these together with the assumptions: they describe different choices of inductor current 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([-2.0, 0.0, 2.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} A -> {output_value:.6g} J")
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 inductor current; the vertical axis shows magnetic stored energy. 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(-2.0, 2.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("Inductor current (A)")
ax.set_ylabel("Magnetic stored energy (J)")
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 magnetic stored energy change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 1 A is 0.1 in those ratio units. Locally, the output increases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.
\[f'(q) = 0.1 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 = 1.02
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, "J")
print("Full expression:", full_prediction, "J")
print("Approximation difference:", full_prediction - linear_prediction, "J")
Here the changed input is 1.02 A. The tangent estimate is 0.052 J, while the full expression gives 0.05202 J. 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 = 4.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 inductor current inside the stated interval, predict whether magnetic stored energy 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: Core saturation and hysteresis require a different energy relation. 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 J: 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(2.0) - evaluate(-2.0))
for points in [101, 201, 401]:
grid = np.linspace(-2.0, 2.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.