Skip to content

Commit

Permalink
Add support for comparisons with 0
Browse files Browse the repository at this point in the history
Implement the following special behaviour when comparing a quantity
against zero:

a) comparing against (non-quantity) zero is allowed for any quantity
b) comparing against zero-magnitude quantities of incompatible
dimensionality raises a Dimensionality error, except for the case
of equality, for which it always returns False

Notes:
1.- Numpy arrays of zeros are also supported and the comparison rules
apply elementwise
2.- In the case of non-multiplicative units, the rules above
apply after converting to base units if the autoconvert offset flag
is set. Otherwise they raise an OffsetUnitCalculusError.
  • Loading branch information
Carlos Pascual committed Apr 13, 2018
1 parent bf33e99 commit c4d5388
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions pint/quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,6 +1090,20 @@ def __eq__(self, other):
# We compare to the base class of Quantity because
# each Quantity class is unique.
if not isinstance(other, _Quantity):
if _eq(other, 0, True):
# Handle the special case in which we compare to zero
# (or an array of zeros)
if self._is_multiplicative:
# compare magnitude
return _eq(self._magnitude, other, False)
else:
# compare the magnitude after converting the
# non-multiplicative quantity to base units
if self._REGISTRY.autoconvert_offset_to_baseunit:
return _eq(self.to_base_units()._magnitude, other, False)
else:
raise OffsetUnitCalculusError(self._units)

return (self.dimensionless and
_eq(self._convert_magnitude(UnitsContainer()), other, False))

Expand All @@ -1115,6 +1129,19 @@ def compare(self, other, op):
if not isinstance(other, self.__class__):
if self.dimensionless:
return op(self._convert_magnitude_not_inplace(UnitsContainer()), other)
elif _eq(other, 0, True):
# Handle the special case in which we compare to zero
# (or an array of zeros)
if self._is_multiplicative:
# compare magnitude
return op(self._magnitude, other)
else:
# compare the magnitude after converting the
# non-multiplicative quantity to base units
if self._REGISTRY.autoconvert_offset_to_baseunit:
return op(self.to_base_units()._magnitude, other)
else:
raise OffsetUnitCalculusError(self._units)
else:
raise ValueError('Cannot compare Quantity and {}'.format(type(other)))

Expand Down

0 comments on commit c4d5388

Please sign in to comment.