pythonsympydimensionunits-of-measurement

"register" a unit and prefix with sympy?


import sympy.physics.units as u
u.find_unit('cm')  # -->  'cm' found
u.find_unit('km')  # -->  'km' found

# so I can do
float(u.convert_to(2 * u.cm, u.km) / u.km)

Now I would like to register nF (nano-farads), pF (pico-farads), and uF (micro-farads) so I can do quick conversions like this (and in other complex calculations):

float(u.convert_to(2 * u.uF, u.nF) / u.nF)

One idea I have is to do this:

u.uF = 1e-6 * u.F
u.nF = 1e-9 * u.F
float(u.convert_to(36 * u.uF, u.nF) / u.nF)

Is there any harm in this? One issue I see is that if I keep the unit, it will only be represented in the base (F). Also I'd need to check to ensure I'm not overwriting any attibutes of u. Further, u.find_unit("nF") returns a blank list.

There aren't many good references on how to apply prefixes in our units.


Solution

  • If you look in sympy.physics.units.definitions.unit_definitions.py you will see examples of how to set definitions like

    mg = milligram = milligrams = Quantity("milligram", abbrev="mg")
    mg.set_global_relative_scale_factor(milli, gram)
    

    So

    >>> from sympy.physics.units import *
    >>> nf=Quantity('nanoFarad', abbrev='nF')
    >>> nf.set_global_relative_scale_factor(nano, farad)
    >>> nf
    nF
    >>> nf.convert_to(farad)
    F/1000000000