[Python-ideas] SI scale factors in Python
Ken Kundert
python-ideas at shalmirane.com
Thu Aug 25 16:06:05 EDT 2016
Here is a fairly typical example that illustrates the usefulness of supporting
SI scale factors and units in Python.
This is simple simulation code that is used to test a current mirror driving an
100kOhm resistor ...
Here is some simulation code that uses SI scale factors
for delta in [-500nA, 0, 500nA]:
input = 2.75uA + delta
wait(1us)
expected = 100kOhm*(2.75uA + delta)
tolerance = 2.2mV
fails = check_output(expected, tolerance)
print('%s: I(in)=%rA, measured V(out)=%rV, expected V(out)=%rV, diff=%rV.' % (
'FAIL' if fails else 'pass',
input, get_output(), expected, get_output() - expected
))
with the output being:
pass: I(in)=2.25uA, measured V(out)=226.7mV, expected V(out)=225mV, diff=1.7mV.
pass: I(in)=2.75uA, measured V(out)=276.8mV, expected V(out)=275mV, diff=1.8mV.
FAIL: I(in)=3.25uA, measured V(out)=327.4mV, expected V(out)=325mV, diff=2.4mV.
And the same code in Python today ...
for delta in [-5e-7, 0, 5e-7]:
input = 2.75e-6 + delta
wait(1e-6)
expected = 1e5*(2.75e-6 + delta)
tolerance = 2.2e-3
fails = check_output(expected, tolerance)
print('%s: I(in)=%eA, measured V(out)=%eV, expected V(out)=%eV, diff=%eV.' % (
'FAIL' if fails else 'pass',
input, get_output(), expected, get_output() - expected
))
with the output being:
pass: I(in)=2.25e-6A, measured V(out)=226.7e-3V, expected V(out)=225e-3V, diff=1.7e-3V.
pass: I(in)=2.75e-6A, measured V(out)=276.8e-3V, expected V(out)=275e-3V, diff=1.8e-3V.
FAIL: I(in)=3.25e-6A, measured V(out)=327.4e-3V, expected V(out)=325e-3V, diff=2.4e-3V.
There are two things to notice. In the first example the numbers are easier to
read: for example, 500nA is easier to read the 5e-7. Second, there is
information in the units that provides provides useful information. One can
easily see that the input signal is a current and that the output is a voltage.
Furthermore, anybody can look at this code and do a simple sanity check on the
expressions even if they don't understand the system being simulated. They can
check the units on the input and output expressions to assure that they are all
consistent.
-Ken
More information about the Python-ideas
mailing list