From bac01f4fde816322094ce9f742f3b7e2b7cc0971 Mon Sep 17 00:00:00 2001 From: Jean Privat Date: Thu, 20 Nov 2014 09:02:44 -0500 Subject: [PATCH] lib: add Float::is_approx to compare floats Signed-off-by: Jean Privat --- lib/standard/kernel.nit | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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 -- 1.7.9.5