Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(normalize): return non-finite input unchanged and drop the sign of zero (#2112)
Kevin91858bebe1d1
diff --git a/semantica/normalize/number_normalizer.py b/semantica/normalize/number_normalizer.pyindex 5af27615..e64e714c 100644--- a/semantica/normalize/number_normalizer.py+++ b/semantica/normalize/number_normalizer.py@@ -826,11 +826,18 @@ class ScientificNotationHandler:significant_digits: Number of significant digits to preserveReturns:- float: Normalized number with specified significant digits+ float: Normalized number with specified significant digits.+ Non-finite input (inf, -inf, nan) comes back unchanged, and a+ result of zero is returned as 0.0 rather than -0.0."""if number == 0:return 0.0+ # inf has no order of magnitude: abs(inf) stays inf in the loop below.+ # nan keeps the behaviour it had before this guard.+ if not math.isfinite(number):+ return number+# Calculate order of magnitudemagnitude = abs(number)order = 0@@ -844,4 +851,7 @@ class ScientificNotationHandler:# Round to significant digitsrounded = round(magnitude, significant_digits - 1)- return math.copysign(rounded * (10**order), number)+ result = math.copysign(rounded * (10**order), number)+ # copysign turns a zero result into -0.0 for negative input, and that+ # serialises as -0.0. The value is zero, so return the plain zero.+ return 0.0 if result == 0 else resultdiff --git a/tests/normalize/test_number_normalizer.py b/tests/normalize/test_number_normalizer.pyindex 2ce3c382..ebce2e92 100644--- a/tests/normalize/test_number_normalizer.py+++ b/tests/normalize/test_number_normalizer.py@@ -1,3 +1,4 @@+import mathimport unittestfrom semantica.normalize.number_normalizer import (@@ -145,6 +146,22 @@ class TestScientificNotationHandler(unittest.TestCase):self.assertEqual(self.handler.normalize_precision(-1234.5, 2), -1200.0)self.assertEqual(self.handler.normalize_precision(-0.000123, 2), -0.00012)+ def test_normalize_precision_returns_non_finite_inputs(self):+ self.assertEqual(+ self.handler.normalize_precision(float("inf"), 2), float("inf")+ )+ self.assertEqual(+ self.handler.normalize_precision(float("-inf"), 2), float("-inf")+ )+ self.assertTrue(+ math.isnan(self.handler.normalize_precision(float("nan"), 2))+ )++ def test_normalize_precision_does_not_return_negative_zero(self):+ # round(4.0, -1) is zero, and copysign(0.0, -4) is -0.0, which+ # serialises as -0.0. The value is zero, so the sign is dropped.+ self.assertEqual(repr(self.handler.normalize_precision(-4, 0)), "0.0")+if __name__ == "__main__":unittest.main()