Finding the nearest E96 resistor value in Python

Problem

You want to find the E24/E48/E96 resistor value that is closest to a given exact value programmatically using python.

Solution

Although there are online tools available for this task, it is often useful to be able to integrate scriptable functions into custom software.

I wrote UliEngineering, an Python3-only electronics library that includes resistor selection amongst a lot of other useful functionality.

First, you need to install UliEngineering

sudo pip3 install git+https://github.com/ulikoehler/UliEngineering.git

then, you can use the functions from Resistor.py to compute the nearest value.

For example, if we want to find the nearest value to 1269.5 Ω on the Python3 interactive shell:

>>> from UliEngineering.Electronics.Resistors import *
>>> nearest_resistor(1269.5, sequence=e96)
1270.0

In order to print the value as a human-readable string, you can use the EngineerIO package:

>>> from UliEngineering.EngineerIO
>>> from UliEngineering.Electronics.Resistors import *
>>> auto_format(nearest_resistor, 1269.5, sequence=e96) 
'1.27 kΩ'

Note that auto_format needs the nearest_resistor function itself as first argument, not the result of calling that function. That is because Python3 type annotations are used to tell auto_formatthat nearest_resistor returns a value with unit Ω.