pythonpint

python pint celsius units


I can't define degC as a unit.

After entering

import pint
u=pint.UnitRegistry()

When stating 1*u.degC it outputs 1 degree_Celsius. Seems that it's OK.

When I'm stating 2*u.degC it outputs following error...

>>> 2*u.degC
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "\Lib\site-packages\pint\facets\plain\unit.py", line 147, in __mul__
    return self._REGISTRY.Quantity(1, self._units) * other
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
  File "\Lib\site-packages\pint\facets\plain\quantity.py", line 1010, in __mul__
    return self._mul_div(other, operator.mul)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "\Lib\site-packages\pint\facets\plain\quantity.py", line 103, in wrapped
    return f(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "\Lib\site-packages\pint\facets\plain\quantity.py", line 77, in wrapped
    result = f(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "\Lib\site-packages\pint\facets\plain\quantity.py", line 958, in _mul_div
    raise OffsetUnitCalculusError(self._units, getattr(other, "units", ""))
pint.errors.OffsetUnitCalculusError: Ambiguous operation with offset unit (degree_Celsius). See https://pint.readthedocs.io/en/stable/user/nonmult.html for guidance.

Could someone guide me why it's like this?

I did read documentation and some searches in browser. Unfortunately no progress to direction of solution.

Expectation:

  1. To use degC unit definition in Python with multiple magnitude meanings, not only with 1.
  2. Make calculations using degC unit alias.

Solution

  • The issue here is that temperature degrees are "non-multiplicative". Which makes sense, you can have a weight and double it, but to say that one temperature is some proportion of another doesn't work, unless you're talking about Kelvin, which where 2 degrees might suggest twice as much of something as 1 degree (but I'm no physicist so take that with a grain of salt).

    This portion of the documentation shows how to define a temperature and convert between units:

    >>> from pint import UnitRegistry
    >>> ureg = UnitRegistry()
    >>> ureg.default_format = '.3f'
    >>> Q_ = ureg.Quantity
    >>> home = Q_(25.4, ureg.degC)
    >>> print(home.to('degF'))
    77.720 degree_Fahrenheit
    

    This will let you define different temperatures.

    In your case it would look like

    >>> Q_(2, u.degC)
    <Quantity(2, 'degree_Celsius')>
    

    I'm not sure what you mean by "make calculations using degC alias" but if you'd rephrase the question with a more specific task, I'd be happy to help with that as well.