Skip to content

Commit ee43f49

Browse files
committed
Add isclose() method for Quantity objects
This allows us to compare floating point values without having to use the equality operator. Signed-off-by: Sahas Subramanian <[email protected]>
1 parent 247c081 commit ee43f49

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/frequenz/sdk/timeseries/_quantities.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,24 @@ def isinf(self) -> bool:
100100
"""
101101
return math.isinf(self._base_value)
102102

103+
def isclose(self, other: Self, rel_tol: float = 1e-9, abs_tol: float = 0.0) -> bool:
104+
"""Return whether this quantity is close to another.
105+
106+
Args:
107+
other: The quantity to compare to.
108+
rel_tol: The relative tolerance.
109+
abs_tol: The absolute tolerance.
110+
111+
Returns:
112+
Whether this quantity is close to another.
113+
"""
114+
return math.isclose(
115+
self._base_value,
116+
other._base_value, # pylint: disable=protected-access
117+
rel_tol=rel_tol,
118+
abs_tol=abs_tol,
119+
)
120+
103121
def __repr__(self) -> str:
104122
"""Return a representation of this quantity.
105123

tests/timeseries/test_quantities.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,12 @@ def test_string_representation() -> None:
9191
assert f"{Fz1(-20000)}" == "-20 kHz"
9292

9393

94+
def test_isclose() -> None:
95+
"""Test the isclose method of the quantities."""
96+
assert Fz1(1.024445).isclose(Fz1(1.024445))
97+
assert not Fz1(1.024445).isclose(Fz1(1.0))
98+
99+
94100
def test_addition_subtraction() -> None:
95101
"""Test the addition and subtraction of the quantities."""
96102
assert Quantity(1) + Quantity(1, exponent=0) == Quantity(2, exponent=0)

0 commit comments

Comments
 (0)