From: Jean Privat Date: Thu, 20 Nov 2014 14:02:44 +0000 (-0500) Subject: lib: add Float::is_approx to compare floats X-Git-Tag: v0.6.11~23^2~1 X-Git-Url: http://nitlanguage.org lib: add Float::is_approx to compare floats Signed-off-by: Jean Privat --- diff --git a/lib/standard/kernel.nit b/lib/standard/kernel.nit index 2e9c9ae..2f2df4b 100644 --- a/lib/standard/kernel.nit +++ b/lib/standard/kernel.nit @@ -331,6 +331,21 @@ universal Float end end + # Compare float numbers with a given precision. + # + # Because of the loss of precision in floating numbers, + # the `==` method is often not the best way to compare them. + # + # ~~~ + # assert 0.01.is_approx(0.02, 0.1) == true + # assert 0.01.is_approx(0.02, 0.001) == false + # ~~~ + fun is_approx(other, precision: Float): Bool + do + assert precision >= 0.0 + return self <= other + precision and self >= other - precision + end + redef fun max(other) do if self < other then