TExcelTAD
Home › EE Foundations: Units, Measurement, Safety & the Lab Notebook › A Python Toolkit for EE Calculations

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

input text"4.7k", "10 mA" SI floats only4700.0, 0.01 formatted output3.837 V, 816.3 uA parse format all arithmetic happens in the middle box, in V, A, ohm, s, F, H

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 Ω⋅F=s\Omega \cdot \text{F} = \text{s} needs no conversion factor.

python · try it yourself
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.

python · try it yourself
# 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 2000 mAh2000\ \text{mAh} at a nominal 3.7 V3.7\ \text{V}, and loads of 5050, 150150 and 500 mA500\ \text{mA}.

Find: the stored charge in coulombs, the energy in kilojoules and watt-hours, and the ideal runtime at each load.

Solve:

Q=2000×10−3 A×3600 s=7200 CE=QV=7200 C×3.7 V=26 640 J=26.64 kJ=26 640 J3600 s/h=7.40 Wht150=2.000 A h0.150 A=13.3 h\begin{aligned} Q &= 2000 \times 10^{-3}\ \text{A} \times 3600\ \text{s} = 7200\ \text{C} \\ E &= Q V = 7200\ \text{C} \times 3.7\ \text{V} = 26\,640\ \text{J} = 26.64\ \text{kJ} = \frac{26\,640\ \text{J}}{3600\ \text{s/h}} = 7.40\ \text{Wh} \\ t_{150} &= \frac{2.000\ \text{A h}}{0.150\ \text{A}} = 13.3\ \text{h} \end{aligned}

Check: 1 Wh=3600 J1\ \text{Wh} = 3600\ \text{J}, and 2 Ah×3.7 V=7.4 Wh2\ \text{Ah} \times 3.7\ \text{V} = 7.4\ \text{Wh} 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).

python · try it yourself
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 VV–II line than from one reading: the fit averages the scatter and reveals offsets. For a straight line V=RI+cV = R I + c fitted by least squares to nn points,

R=∑(Ii−Iˉ)(Vi−Vˉ)∑(Ii−Iˉ)2,s=∑ri2n−2,u(R)=s∑(Ii−Iˉ)2R = \frac{\sum (I_i - \bar I)(V_i - \bar V)}{\sum (I_i - \bar I)^2}, \qquad s = \sqrt{\frac{\sum r_i^2}{n - 2}}, \qquad u(R) = \frac{s}{\sqrt{\sum (I_i - \bar I)^2}}

where rir_i 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.

python · try it yourself
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 R=470.7 ΩR = 470.7\ \Omega with a standard uncertainty of only 0.3 Ω0.3\ \Omega. 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 0.5 %0.5\,\% on volts and, say, 1 %1\,\% on milliamperes, the Type B part is about 0.52+12 %/3≈0.65 %\sqrt{0.5^2 + 1^2}\,\% / \sqrt{3} \approx 0.65\,\%, or 3 Ω3\ \Omega (Accuracy, Precision and Measurement Uncertainty). An honest result is R=471±6 ΩR = 471 \pm 6\ \Omega (k=2k = 2), consistent with a 470 Ω470\ \Omega, 1 %1\,\% part.

Guided lab: a V-I characteristic of a resistor

Hand calculation. A 470 Ω470\ \Omega resistor at 11, 22, 33, 44, 5 V5\ \text{V} takes 2.132.13, 4.264.26, 6.386.38, 8.518.51, 10.64 mA10.64\ \text{mA} and at most 53 mW53\ \text{mW}.

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 20 mA20\ \text{mA}) from 00 to 5 V5\ \text{V} in 1 V1\ \text{V} 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 1 %1\,\% 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 5 V5\ \text{V} DC from a current-limited supply; no mains.
  • Keep each resistor below its power rating: the program flags 12 V12\ \text{V} on 470 Ω470\ \Omega (306 mW306\ \text{mW}) as too much for a 0.25 W0.25\ \text{W} part.
  • The ammeter goes in series; never across the supply.

Pitfalls

  • Mixing prefixed and SI values in one formula (I_mA used 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 with float().
  • Typing data into code: keep raw readings in files under version control.

Practice

  1. Write the SI value of 33 μF33\ \mu\text{F} and of 2.2 MΩ2.2\ \text{M}\Omega as floats.
  2. What does the units checker print for V * V / R with V=12 VV = 12\ \text{V} and R=24 ΩR = 24\ \Omega?
  3. A cell is rated 800 mAh800\ \text{mAh} at 1.2 V1.2\ \text{V}. What is its energy in joules?
Answer
  1. 33e-6 and 2.2e6.
  2. 6 W: V2/Ω\text{V}^2/\Omega has the dimensions of a watt.
  3. 0.8 A×3600 s×1.2 V=3456 J0.8\ \text{A} \times 3600\ \text{s} \times 1.2\ \text{V} = 3456\ \text{J}.

Test yourself

Why store every quantity in coherent SI units inside a program?

  1. Python cannot handle prefixes
  2. Formulas then need no conversion factors, so Ohm's law is just V / R
  3. It makes numbers smaller
  4. Matplotlib requires it

In the toolkit's parse, what is parse("2.2M")?

  1. 0.0022
  2. 2200.0
  3. 2200000.0
  4. an error

A least-squares fit gives R=470.7 ΩR = 470.7\ \Omega with a standard error of 0.3 Ω0.3\ \Omega. What does that 0.3 Ω0.3\ \Omega leave out?

  1. Nothing
  2. The scatter of the points
  3. Systematic gain errors of the meters, which shift every point the same way
  4. The number of points

How many joules are in 1 Wh1\ \text{Wh}?

  1. 60
  2. 1000
  3. 3600
  4. 3.6