fix for comparing infinities (#16122)

This commit is contained in:
Antonis Geralis 2020-11-25 11:15:34 +02:00 • committed by GitHub
commit e220f756e7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -177,6 +177,17 @@ proc almostEqual*[T: SomeFloat](x, y: T; unitsInLastPlace: Natural = 4): bool {.
runnableExamples: runnableExamples:
doAssert almostEqual(3.141592653589793, 3.1415926535897936) doAssert almostEqual(3.141592653589793, 3.1415926535897936)
doAssert almostEqual(1.6777215e7'f32, 1.6777216e7'f32) 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) let diff = abs(x - y)
result = diff <= epsilon(T) * abs(x + y) * T(unitsInLastPlace) or result = diff <= epsilon(T) * abs(x + y) * T(unitsInLastPlace) or
diff < minimumPositiveValue(T) diff < minimumPositiveValue(T)