pythontemperatureunit-conversionpint

Python pint convert 1/°Fahrenheit to 1/°Celsius


I use the python package pint and want to calculate e.g. 1 m/°F to m/°C.

from pint import UnitRegistry

ureg = UnitRegistry() #autoconvert_offset_to_baseunit = True
quantity = ureg.Quantity
fromvalue = quantity(1, ureg.parse_expression("m/°F"))
result = fromvalue.to(ureg.parse_expression("m/°C"))

print(result)

I get the error: "OffsetUnitCalculusError: Ambiguous operation with offset unit (meter, degree_Fahrenheit). See https://pint.readthedocs.io/en/stable/user/nonmult.html for guidance.".

I read the explanation from the page linked in the error message. It helps to understand the problem, but doesn't provide a solution.

If I use ureg = UnitRegistry(autoconvert_offset_to_baseunit = True) or as_delta=False in the parsing, I get 1 meter / kelvin as a reault, which is wrong.

I am expecting 1 m/°F -> 5/9 m/°C as calculated by hand below?

1 m/°F        = x m/°C 
1 m/Δ°F       = x m/Δ°C 
1 m/(9/5 Δ°C) = x m/Δ°C 
5/9 m/Δ°C     = x m/Δ°C 
5/9 m/Δ°C     = 5/9 m/Δ°C  

1 m/°F -> 5/9 m/°C   

One additional complication is that I'm making a function to convert values from one unit to another, so conversions e.g. from °F to °C should still work with the settings.


Solution

  • You are using the wrong string representation for the unit you actually want.

    >>> quantity(1, ureg.parse_expression("m/Δ°F"))
    <Quantity(1, 'meter / delta_degree_Fahrenheit')>