From e220f756e795b972b72d4e8b9d729d1d9b73d2e2 Mon Sep 17 00:00:00 2001 From: Antonis Geralis <43617260+planetis-m@users.noreply.github.com> Date: Wed, 25 Nov 2020 11:15:34 +0200 Subject: [PATCH] fix for comparing infinities (#16122) --- lib/pure/math.nim | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index af31a57851..ccd766f461 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -177,6 +177,17 @@ proc almostEqual*[T: SomeFloat](x, y: T; unitsInLastPlace: Natural = 4): bool {. runnableExamples: doAssert almostEqual(3.141592653589793, 3.1415926535897936) doAssert almostEqual(1.6777215e7'f32, 1.6777216e7'f32) + doAssert almostEqual(Inf, Inf) + doAssert almostEqual(-Inf, -Inf) + doAssert almostEqual(Inf, -Inf) == false + doAssert almostEqual(-Inf, Inf) == false + doAssert almostEqual(Inf, NaN) == false + doAssert almostEqual(NaN, NaN) == false + + if x == y: + # short circuit exact equality -- needed to catch two infinities of + # the same sign. And perhaps speeds things up a bit sometimes. + return true let diff = abs(x - y) result = diff <= epsilon(T) * abs(x + y) * T(unitsInLastPlace) or diff < minimumPositiveValue(T)