A Python Toolkit for EE Calculations
Spreadsheets and calculators are fine for one resistor. They become a liability for twenty readings, five tolerance corners or a plot for a report: retyped numbers, a lost factor of 1000, a formula that silently refers to the wrong cell. A short Python program is repeatable, checkable and can be committed to Git next to the data. This lesson builds the small toolkit the rest of the track assumes: SI values with prefixes handled by hand, a tiny units checker, NumPy arrays for many readings at once, a least-squares fit with an honest uncertainty, and one clean plot of a measurement. The Python, NumPy and Matplotlib courses teach the languages and libraries in depth; here they are applied.
The rule: SI inside, prefixes at the edges
Every quantity is stored as a plain float in the coherent SI unit (SI Units and Prefixes): volts, amperes, ohms, seconds, farads, henries, watts. Prefixes appear only when reading input and printing results. A variable that must hold something else says so in its name (I_mA, t_ms, capacity_mAh) and is converted on the next line. With that one rule, Ohm's law in code is just V / R, and needs no conversion factor.
import math
PREFIX = {"p": 1e-12, "n": 1e-9, "u": 1e-6, "m": 1e-3, "": 1.0, "k": 1e3, "M": 1e6, "G": 1e9}
def parse(text):
"""'4.7k' -> 4700.0, '100n' -> 1e-07, '12' -> 12.0 (SI value, unit symbol not included)."""
text = text.strip()
if text and text[-1] in PREFIX and not text[-1].isdigit():
return float(text[:-1]) * PREFIX[text[-1]]
return float(text)
def eng(x, unit):
"""Format an SI value with an engineering prefix: eng(0.0008163, 'A') -> '816.3 uA'."""
if x == 0:
return f"0 {unit}"
exp3 = int(math.floor(math.log10(abs(x)) / 3)) * 3
exp3 = max(-12, min(9, exp3))
name = {v: k for k, v in {"p": -12, "n": -9, "u": -6, "m": -3, "": 0, "k": 3, "M": 6, "G": 9}.items()}[exp3]
return f"{x / 10**exp3:.4g} {name}{unit}"
R1, R2, V1 = parse("10k"), parse("4.7k"), parse("12")
I = V1 / (R1 + R2)
print(eng(I, "A"), eng(I * R2, "V"), eng(I**2 * R1, "W"))
print(eng(parse("100n"), "F"), eng(parse("2.2M"), "ohm"), eng(1 / (2 * math.pi * 1e3 * 100e-9), "Hz"))816.3 uA 3.837 V 6.664 mW
100 nF 2.2 Mohm 1.592 kHz
Note the difference from SPICE (The EE Software Toolchain): here M is mega and m is milli, as in SI; in a SPICE deck both mean milli. Always know which convention a tool uses.
A tiny units checker
Plain floats cannot catch the mistake of adding a voltage to a current. A dozen lines can: store each value with the exponents of the SI base units (kilogram, metre, second, ampere), add exponents when multiplying, subtract them when dividing, and refuse to add values whose exponents differ. This is Dimensional Analysis done by the computer.
# A tiny units checker: a value plus exponents of the SI base units (kg, m, s, A)
NAMES = {(1, 2, -3, -1): "V", (0, 0, 0, 1): "A", (1, 2, -3, -2): "ohm", (1, 2, -3, 0): "W",
(1, 2, -2, 0): "J", (0, 0, 1, 0): "s", (0, 0, 1, 1): "C", (0, 0, 0, 0): ""}
class Q:
def __init__(self, value, dims):
self.value, self.dims = value, tuple(dims)
def __mul__(self, other):
return Q(self.value * other.value, [a + b for a, b in zip(self.dims, other.dims)])
def __truediv__(self, other):
return Q(self.value / other.value, [a - b for a, b in zip(self.dims, other.dims)])
def __add__(self, other):
if self.dims != other.dims:
raise TypeError(f"cannot add {self.unit()} and {other.unit()}")
return Q(self.value + other.value, self.dims)
def unit(self):
return NAMES.get(self.dims, str(self.dims))
def __repr__(self):
return f"{self.value:.4g} {self.unit()}"
volt, amp, second = Q(1, (1, 2, -3, -1)), Q(1, (0, 0, 0, 1)), Q(1, (0, 0, 1, 0))
V = Q(12, volt.dims)
I = Q(0.5, amp.dims)
R = V / I
P = V * I
E = P * Q(60, second.dims)
print("R =", R, "| P =", P, "| E in one minute =", E, "| Q =", I * Q(60, second.dims))
try:
print(V + I)
except TypeError as err:
print("caught:", err)R = 24 ohm | P = 6 W | E in one minute = 360 J | Q = 30 C
caught: cannot add V and A
Real projects use a library for this (for example pint), but writing the small version once shows what such libraries do.
Many readings at once with NumPy
NumPy applies one formula to a whole array, so five supply settings need one line, and a check against the resistor's power rating needs one more.
Worked example: from milliampere-hours to joules
Given: a cell rated at a nominal , and loads of , and .
Find: the stored charge in coulombs, the energy in kilojoules and watt-hours, and the ideal runtime at each load.
Solve:
Check: , and directly. Real runtimes are shorter: capacity falls at high current and low temperature, and a device stops before the cell is empty. Do not test that by deep-discharging or charging lithium cells on the bench (ESD, Stored Energy and Battery Hazards).
import numpy as np
V_set = np.array([1.0, 2.0, 3.3, 5.0, 12.0]) # volts
R = 470.0 # ohms
I = V_set / R # amperes, one division for all five
P = V_set**2 / R # watts
for v, i, p in zip(V_set, I, P):
flag = " <- over a 0.25 W resistor rating" if p > 0.25 else ""
print(f"{v:5.1f} V -> {i * 1e3:6.2f} mA, {p * 1e3:7.2f} mW{flag}")
capacity_mAh, V_cell = 2000, 3.7
charge_C = capacity_mAh * 1e-3 * 3600 # mAh -> A*h -> A*s = C
energy_J = charge_C * V_cell
print(f"{capacity_mAh} mAh at {V_cell} V = {charge_C:.0f} C = {energy_J / 1e3:.2f} kJ = {energy_J / 3600:.2f} Wh")
loads_A = np.array([50, 150, 500]) * 1e-3
hours = capacity_mAh * 1e-3 / loads_A
print("ideal runtime (h):", [round(float(h), 1) for h in hours]) 1.0 V -> 2.13 mA, 2.13 mW
2.0 V -> 4.26 mA, 8.51 mW
3.3 V -> 7.02 mA, 23.17 mW
5.0 V -> 10.64 mA, 53.19 mW
12.0 V -> 25.53 mA, 306.38 mW <- over a 0.25 W resistor rating
2000 mAh at 3.7 V = 7200 C = 26.64 kJ = 7.40 Wh
ideal runtime (h): [40.0, 13.3, 4.0]
Fitting a line to a measurement, and its uncertainty
A resistance is better found from a – line than from one reading: the fit averages the scatter and reveals offsets. For a straight line fitted by least squares to points,
where are the residuals. The formulas are written out instead of calling np.polyfit(..., cov=True), whose scaling of the covariance has changed between NumPy versions.
import numpy as np
import matplotlib.pyplot as plt
# Measured: supply stepped 0..5 V across a nominal 470 ohm resistor; I read on the mA range
I_mA = np.array([0.00, 2.13, 4.25, 6.38, 8.51, 10.62]) # milliamperes, as read
V = np.array([0.000, 1.002, 2.001, 2.998, 4.004, 5.001]) # volts, as read
I = I_mA * 1e-3 # to SI at the edge
u_V = 0.005 * V + 0.003 # example spec limit, volts (for the error bars)
n = len(I)
Ibar, Vbar = I.mean(), V.mean()
Sxx = float(np.sum((I - Ibar)**2))
slope = float(np.sum((I - Ibar) * (V - Vbar)) / Sxx) # ohms
icpt = float(Vbar - slope * Ibar) # volts
resid = V - (slope * I + icpt)
s = float(np.sqrt(np.sum(resid**2) / (n - 2)))
u_slope = s / np.sqrt(Sxx)
print(f"R = {slope:.1f} ohm, standard uncertainty of the fit {u_slope:.1f} ohm")
print(f"intercept = {icpt * 1e3:.1f} mV, residual s = {s * 1e3:.2f} mV")
print(f"through the origin: R = {float(np.sum(I * V) / np.sum(I**2)):.1f} ohm")
fig, ax = plt.subplots(figsize=(5, 3.4))
ax.errorbar(I_mA, V, yerr=u_V, fmt="o", capsize=3, label="measured (spec limits)")
Ifit = np.linspace(0, 11, 2)
ax.plot(Ifit, slope * Ifit * 1e-3 + icpt, label=f"fit: R = {slope:.0f} ohm")
ax.set_xlabel("I (mA)")
ax.set_ylabel("V (V)")
ax.legend()
ax.grid(True, alpha=0.3)
fig.tight_layout()
plt.show()R = 470.7 ohm, standard uncertainty of the fit 0.3 ohm
intercept = -0.9 mV, residual s = 2.74 mV
through the origin: R = 470.6 ohm
The fit says with a standard uncertainty of only . That number covers the scatter of the points (Type A) and nothing else. Both meters also have gain errors, which shift every point by the same fraction and so cannot show up in the residuals: with the example spec of on volts and, say, on milliamperes, the Type B part is about , or (Accuracy, Precision and Measurement Uncertainty). An honest result is (), consistent with a , part.
Guided lab: a V-I characteristic of a resistor
Hand calculation. A resistor at , , , , takes , , , , and at most .
Simulation. Run the vectorised program with your own settings, then the fit with your own readings.
What you would measure. Step a bench supply (current limit ) from to in steps, with one meter across the resistor and one in series on its mA range. Expect points on a straight line through the origin within a few millivolts, a fitted slope within about of the colour code, and an intercept within a few millivolts of zero (a larger one points to an offset or a burden-voltage problem). Save the readings as a CSV file in your lab repository and load them with np.loadtxt instead of typing them into the program.
Hazards and safe setup.
- At most DC from a current-limited supply; no mains.
- Keep each resistor below its power rating: the program flags on () as too much for a part.
- The ammeter goes in series; never across the supply.
Pitfalls
- Mixing prefixed and SI values in one formula (
I_mAused as amperes is a factor-1000 error). - Using the fit's standard error as the whole uncertainty.
- Printing NumPy scalars inside lists (they show as
np.float64(...)in NumPy 2): convert withfloat(). - Typing data into code: keep raw readings in files under version control.
Practice
- Write the SI value of and of as floats.
- What does the units checker print for
V * V / Rwith and ? - A cell is rated at . What is its energy in joules?
Answer
33e-6and2.2e6.6 W: has the dimensions of a watt.- .
Test yourself
Why store every quantity in coherent SI units inside a program?
- Python cannot handle prefixes
- Formulas then need no conversion factors, so Ohm's law is just
V / R - It makes numbers smaller
- Matplotlib requires it
In the toolkit's parse, what is parse("2.2M")?
- 0.0022
- 2200.0
- 2200000.0
- an error
A least-squares fit gives with a standard error of . What does that leave out?
- Nothing
- The scatter of the points
- Systematic gain errors of the meters, which shift every point the same way
- The number of points
How many joules are in ?
- 60
- 1000
- 3600
- 3.6