From 5d4d17e46e451861563a7b33cf446664cfadf6a6 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Jos=C3=A9=20Fonseca?= Date: Tue, 13 Dec 2011 08:29:55 +0000 Subject: [PATCH] Approximate comparison for floats. --- scripts/jsondiff.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/scripts/jsondiff.py b/scripts/jsondiff.py index b541e44..0a4f7ba 100755 --- a/scripts/jsondiff.py +++ b/scripts/jsondiff.py @@ -137,8 +137,9 @@ class Dumper(Visitor): class Comparer(Visitor): - def __init__(self, ignore_added = False): + def __init__(self, ignore_added = False, tolerance = 2.0 ** -24): self.ignore_added = ignore_added + self.tolerance = tolerance def visit_object(self, a, b): if not isinstance(b, dict): @@ -172,8 +173,13 @@ class Comparer(Visitor): return True def visit_value(self, a, b): - return a == b - + if isinstance(a, float) or isinstance(b, float): + if a == 0: + return abs(b) < self.tolerance + else: + return abs((b - a)/a) < self.tolerance + else: + return a == b class Differ(Visitor): -- 2.43.0