From d886c2066253caf7fb48ee3d86ddd4b270512265 Mon Sep 17 00:00:00 2001 From: andrewgsavage Date: Sun, 15 Dec 2024 12:51:30 +0000 Subject: [PATCH] qto.py: Make nan/inf magnitude checks accept uncertainties (#2093) * qto.py: Make nan/inf magnitude checks accept uncertainties Co-authored-by: Doron Behar --- CHANGES | 1 + pint/facets/plain/qto.py | 12 ++++++------ pint/testsuite/test_issues.py | 20 +++++++++++++++++++- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/CHANGES b/CHANGES index 6b3752f03..e91f11a0c 100644 --- a/CHANGES +++ b/CHANGES @@ -7,6 +7,7 @@ Pint Changelog - Add docs to the functions in ``pint.testing`` (PR #2070) - Fix round function returning float instead of int (#2081) - Update constants to CODATA 2022 recommended values. (#2049) +- Fixed issue with `.to_compact` and Magnitudes with uncertainties / Quantities with units (PR #2069, issue #2044) 0.24.4 (2024-11-07) diff --git a/pint/facets/plain/qto.py b/pint/facets/plain/qto.py index 22176491d..9d8b7f611 100644 --- a/pint/facets/plain/qto.py +++ b/pint/facets/plain/qto.py @@ -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] = {} diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py index 847f269f0..8501661d0 100644 --- a/pint/testsuite/test_issues.py +++ b/pint/testsuite/test_issues.py @@ -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") @@ -1331,3 +1331,21 @@ def test_issue2007(): assert f"{q:~C}" == "1" assert f"{q:~D}" == "1" assert f"{q:~H}" == "1" + + +@helpers.requires_uncertainties() +@helpers.requires_numpy() +def test_issue2044(): + from numpy.testing import assert_almost_equal + from uncertainties import ufloat + + 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 == "kilometer" + + # Similarly, for a Ufloat with units + q = (ufloat(10_000, 0.01) * ureg.m).to_compact() + assert_almost_equal(q.m.n, 10.0) + assert q.u == "kilometer"