Circuit diagrams can look different while expressing the same two conservation ideas. Kirchhoff's current law tracks charge at each node. Kirchhoff's voltage law tracks energy per unit charge around a closed path. When every element is linear, these laws and the element equations form a linear system that a computer can assemble from a graph.
The graph viewpoint matters. Nodes are electrically connected regions treated as having one potential. Branches are elements joining pairs of nodes. The drawing's shape and wire lengths usually carry no mathematical meaning in the lumped-circuit approximation.
Charge conservation says that net current into a node equals the rate at which charge is stored there. If every branch current \(I_k\) is defined positive into the node, then the general statement is
\[\sum_k I_k=\frac{dQ_{\mathrm{node}}}{dt}\]In an ideal lumped node, no significant charge accumulates, so this reduces to
\[\sum_k I_k=0\]The signs come from chosen branch orientations. A calculated negative current simply means the physical current is opposite the chosen arrow. It is usually safer to retain one stable orientation than to redraw the arrow after seeing an answer.
Voltage is electric potential energy per unit charge. For a closed circuit loop in the usual lumped, quasistatic approximation, the oriented voltage changes sum to zero:
\[\sum_k \Delta V_k=0\]Traverse the loop in either direction and use each element's assigned polarity. A rise is positive and a drop is negative, or vice versa, as long as the rule is consistent. Reversing the traversal multiplies the whole equation by \(-1\) and changes no physics.
Kirchhoff's voltage law in this form assumes that a changing magnetic flux through the loop does not create a significant induced electromotive force that has been omitted from the circuit model. If induction matters, Faraday's law supplies the additional term.
Kirchhoff's laws describe topology and conservation, but they do not say how an element relates its branch voltage and current. A resistor with current directed from node \(a\) to node \(b\) obeys
\[I_{a\to b}=\frac{V_a-V_b}{R}\]An ideal voltage source instead fixes its terminal voltage. An ideal current source fixes its branch current. These constitutive relations, combined with KCL or KVL, determine the unknown operating point.
For a resistor-only node connected to neighbors, KCL becomes
\[\sum_{b}\frac{V_a-V_b}{R_{ab}}=I_{\mathrm{injected},a}\]Here \(I_{\mathrm{injected},a}\) is positive for current supplied into the node by independent current sources. The equation has units of amperes on both sides.
Only voltage differences affect ordinary branch equations. Adding the same constant to every node potential leaves all branch voltages and currents unchanged. Without another constraint, the node-voltage matrix therefore has no unique solution.
Choose one reference node and define its voltage as zero. This is a coordinate choice, not a claim that the node contains no charge or has an absolute potential of zero. A different reference changes the listed node potentials by a common offset while leaving all measurable voltage differences, currents, and powers unchanged.
Disconnected or floating subnetworks may need their own reference or an additional physical connection. A solver reporting a singular matrix is useful evidence, but the application should translate that numerical result into a circuit-level explanation.
It is convenient to write conductance as
\[G_{ab}=\frac{1}{R_{ab}}\]After removing the reference-node voltage from the unknowns, a linear resistor network with current injections can be written
\[\mathbf G\mathbf v=\mathbf i\]Each diagonal matrix entry is the sum of conductances incident on that node. An off-diagonal entry is the negative of the conductance directly connecting the two nodes. With positive resistances, the matrix is symmetric. For a connected resistor network with a fixed reference, it is also positive definite, which supports stable specialized solvers.
import numpy as np
# Nodes 0 and 1 are unknown; node 2 is the ground reference.
conductance = np.zeros((3, 3))
for first, second, resistance in [(0, 1, 1000.0), (0, 2, 2000.0), (1, 2, 1000.0)]:
g = 1 / resistance
conductance[first, first] += g
conductance[second, second] += g
conductance[first, second] -= g
conductance[second, first] -= g
injection = np.array([0.003, 0.0])
voltage = np.linalg.solve(conductance[:2, :2], injection)
print("Node voltages (V):", voltage)
When one endpoint is the reference, only the non-reference diagonal contribution remains in the reduced matrix. Care is also needed when stamping current-source signs: the source adds current at the node it enters and removes current at the node it leaves.
Ideal voltage sources between unknown nodes do not fit the simplest conductance-only equations because their current is not known from a conductance. One can use a supernode or modified nodal analysis, which adds the source current as an unknown and the source voltage relation as another equation.
A branch-node incidence matrix records the graph without using coordinates. For each oriented branch, put \(+1\) at the node where the branch enters, \(-1\) where it leaves, and zero elsewhere. If \(\mathbf A\) is defined with that convention and \(\mathbf i_b\) contains oriented branch currents, KCL can be written
\[\mathbf A\mathbf i_b=\mathbf 0\]The same topology maps node potentials to branch voltage differences, with a transpose and a sign determined by the chosen incidence convention. Different books may reverse every branch convention; the resulting matrices look different but produce identical physical differences and currents when used consistently.
Consider a \(12\ \mathrm V\) node connected through a \(3\ \Omega\) to an unknown middle node. A second \(3\ \Omega\) connects the middle node to the zero-volt reference. KCL at the middle node is
\[\frac{V_m-12\ \mathrm V}{3\ \Omega} +\frac{V_m-0}{3\ \Omega}=0\]Multiplying through and collecting terms gives
\[2V_m-12\ \mathrm V=0, \qquad V_m=6\ \mathrm V\]The current through each resistor has magnitude
\[I=\frac{12\ \mathrm V-6\ \mathrm V}{3\ \Omega} =2\ \mathrm A\]At the middle node, two amperes enter from the upper resistor and two amperes leave through the lower resistor. The source delivers \(24\ \mathrm W\), and each resistor absorbs \(12\ \mathrm W\). Charge balance and power balance both close.
After solving a general system
\[\mathbf M\mathbf x=\mathbf b\]recompute the residual
\[\mathbf r=\mathbf M\mathbf x-\mathbf b\]A small residual shows that the numerical result satisfies the equations that were assembled. It does not prove the graph, units, source signs, or component values are correct. Therefore also reconstruct every branch current, check KCL at nodes that were not used as independent rows, check voltage sums around selected loops, and compare total power supplied with total power absorbed.
residual = conductance[:2, :2] @ voltage - injection
assert np.allclose(residual, 0.0)
v0, v1 = voltage
resistor_power = (v0 - v1) ** 2 / 1000 + v0**2 / 2000 + v1**2 / 1000
source_power = -v0 * injection[0]
assert np.isclose(resistor_power + source_power, 0.0)
print("Power balance (W):", resistor_power + source_power)
Use a tolerance scaled to the matrix and expected solution; a fixed absolute tolerance alone can be misleading when values span many orders of magnitude. Poor conditioning can amplify rounding error even when the circuit is physically well specified.
This formulation assumes lumped components, ideal wires, linear resistors, and usually a steady DC operating point. Real sources have internal resistance and operating limits. Real components heat, vary with tolerance, and acquire parasitic capacitance and inductance. Capacitors and inductors introduce time-dependent state; diodes and transistors introduce nonlinear equations. Long conductors and high frequencies require distributed electromagnetic models because propagation delay and radiation matter.
Within its domain, Kirchhoff's laws are powerful precisely because conservation and topology remain separate from element behavior. That separation turns a circuit drawing into data, equations, results, and checks that can all be inspected independently.
Inject current into a node connected to ground through a one kilohm resistor. The question for this calculation is precise: how does node voltage change when we change injected 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.
This one-node case is a benchmark for the conductance-matrix method. 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 0.01 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 injected current, expressed in A. The output is
node voltage, expressed in V. 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 0.003 A, the expression gives 3 V. 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("1000*q", locals={"q": q})
reference_input = 0.003
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "A")
print("Predicted node voltage:", reference_output, "V")
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 V. The midpoint, at 0.005 A, gives 5 V. The upper endpoint gives 10 V. Read these together with the assumptions: they describe different choices of injected 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([0.0, 0.005, 0.01])
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} V")
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 injected current; the vertical axis shows node voltage. 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, 0.01, 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("Injected current (A)")
ax.set_ylabel("Node voltage (V)")
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 node voltage change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 0.003 A is 1000 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) = 1000\]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 = 0.00305
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, "V")
print("Full expression:", full_prediction, "V")
print("Approximation difference:", full_prediction - linear_prediction, "V")
Here the changed input is 0.00305 A. The tangent estimate is 3.05 V, while the full expression gives 3.05 V. 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 = 0.01
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 injected current inside the stated interval, predict whether node voltage 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: This one-node case is a benchmark for the conductance-matrix method. 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 V: 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(0.01) - evaluate(0.0))
for points in [101, 201, 401]:
grid = np.linspace(0.0, 0.01, 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.