Skip to content

Commit

Permalink
qto.py: Make nan/inf magnitude checks accept uncertainties
Browse files Browse the repository at this point in the history
  • Loading branch information
doronbehar committed Oct 26, 2024
1 parent 2839f6e commit 6d54d1d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Pint Changelog
- Switch from appdirs to platformdirs.
- Fixes issues related to GenericPlainRegistry.__getattr__ type (PR #2038, Issues #1946 and #1804)
- Removed deprecated references in documentation and tests (PR #2058, Issue #2057)
- Fixed issue with `.to_compact` and Magnitudes with uncertainties / Quantities with units (PR #2069, issue #2044)


0.24.1 (2024-06-24)
Expand Down
12 changes: 6 additions & 6 deletions pint/facets/plain/qto.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,12 @@ def to_compact(
)
return quantity

if (
quantity.unitless
or quantity.magnitude == 0
or math.isnan(quantity.magnitude)
or math.isinf(quantity.magnitude)
):
qm = (
quantity.magnitude
if not hasattr(quantity.magnitude, "nominal_value")
else quantity.magnitude.nominal_value
)
if quantity.unitless or qm == 0 or math.isnan(qm) or math.isinf(qm):
return quantity

SI_prefixes: dict[int, str] = {}
Expand Down
17 changes: 16 additions & 1 deletion pint/testsuite/test_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def test_angstrom_creation(self, module_registry):
module_registry.Quantity(2, "Å")

def test_alternative_angstrom_definition(self, module_registry):
module_registry.Quantity(2, "\u212B")
module_registry.Quantity(2, "\u212b")

def test_micro_creation_U03bc(self, module_registry):
module_registry.Quantity(2, "μm")
Expand Down Expand Up @@ -1331,3 +1331,18 @@ def test_issue2007():
assert f"{q:~C}" == "1"
assert f"{q:~D}" == "1"
assert f"{q:~H}" == "1"


@helpers.requires_uncertainties()
def test_issue2044():
ureg = UnitRegistry()
# First make sure this doesn't fail completely (A Measurement)
q = ureg.Quantity(10_000, "m").plus_minus(0.01).to_compact()
assert_almost_equal(q.m.n, 10.0)
assert q.u == "kilometers"
# Similarly, for a Ufloat with units
from uncertainties import ufloat

q = (ufloat(10_000, 0.01) * ureg.m).to_compact()
assert_almost_equal(q.m.n, 10.0)
assert q.u == "kilometers"

0 comments on commit 6d54d1d

Please sign in to comment.