Skip to content

Instantly share code, notes, and snippets.

@natpen
Last active July 15, 2016 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natpen/3d78006798d359d1b406c7f1dda67d12 to your computer and use it in GitHub Desktop.
Save natpen/3d78006798d359d1b406c7f1dda67d12 to your computer and use it in GitHub Desktop.
python recursive fuzzy float comparison
def _is_close(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def _is_fuzzy_equal(expected, actual):
if isinstance(expected, set):
expected = list(expected)
if isinstance(actual, set):
actual = list(actual)
if isinstance(actual, list) or isinstance(actual, tuple):
for index, value in enumerate(actual):
if not _is_fuzzy_equal(expected[index], actual[index]):
return False
return True
if isinstance(actual, dict):
for key, value in actual.iteritems():
if not _is_fuzzy_equal(expected[key], actual[key]):
return False
return True
if isinstance(expected, numbers.Number):
return _is_close(float(expected), float(actual))
return expected == actual
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment