Skip to content

Commit

Permalink
qto.py: Make nan/inf magnitude checks accept uncertainties (#2093)
Browse files Browse the repository at this point in the history
* qto.py: Make nan/inf magnitude checks accept uncertainties


Co-authored-by: Doron Behar <[email protected]>
  • Loading branch information
andrewgsavage and doronbehar authored Dec 15, 2024
1 parent fadbf70 commit d886c20
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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)
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
20 changes: 19 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,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"

0 comments on commit d886c20

Please sign in to comment.