diff options
author | Carlos Pascual <cpascual@cells.es> | 2018-04-13 19:05:19 +0200 |
---|---|---|
committer | Carlos Pascual <cpascual@cells.es> | 2018-04-13 19:07:49 +0200 |
commit | c4d53881b63e60f5173dcec70a9b2a0c3427a242 (patch) | |
tree | 28b3ab283f82744bc8eafdf85f37b8ea416ad529 | |
parent | bf33e991c8d888781d1db87899d7bd2bcb273c98 (diff) | |
download | pint-c4d53881b63e60f5173dcec70a9b2a0c3427a242.tar.gz |
Add support for comparisons with 0
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.
-rw-r--r-- | pint/quantity.py | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/pint/quantity.py b/pint/quantity.py index c6e1284..88bfdac 100644 --- a/pint/quantity.py +++ b/pint/quantity.py @@ -1090,6 +1090,20 @@ class _Quantity(PrettyIPython, SharedRegistryObject): # 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)) @@ -1115,6 +1129,19 @@ class _Quantity(PrettyIPython, SharedRegistryObject): 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))) |