Search code examples
pythonmathsymbolic-mathsympy

Units conversion in Python


SymPy is a great tool for doing units conversions in Python:

>>> from sympy.physics import units
>>> 12. * units.inch / units.m
0.304800000000000

You can easily roll your own:

>>> units.BTU = 1055.05585 * units.J
>>> units.BTU
1055.05585*m**2*kg/s**2

However, I cannot implement this into my application unless I can convert degrees C (absolute) to K to degrees F to degrees R, or any combo thereof.

I thought maybe something like this would work:

units.degC = <<somefunc of units.K>>

But clearly that is the wrong path to go down. Any suggestions for cleanly implementing "offset"-type units conversions in SymPy?

Note: I'm open to trying other units conversion modules, but don't know of any besides Unum, and found it to be cumbersome.

Edit: OK, it is now clear that what I want to do is first determine if the two quantities to be compared are in the same coordinate system. (like time units reference to different epochs or time zones or dB to straight amplitude), make the appropriate transformation, then make the conversion. Are there any general coordinate system management tools? That would be great.

I would make the assumption that °F and °C always refer to Δ°F Δ°C within an expression but refer to absolute when standing alone. I was just wondering if there was a way to make units.degF a function and slap a decorator property() on it to deal with those two conditions.

But for now, I'll set units.C == units.K and try to make it very clear in the documentation to use functions convertCtoK(...) and convertFtoR(...) when dealing with absolute units. (Just kidding. No I won't.)


Solution

  • I personally like Quantities thanks to its NumPy integration, however it only does relative temperatures, not absolute.