Skip to content

Instantly share code, notes, and snippets.

@jterrace
Created February 14, 2012 18:30
Show Gist options
  • Save jterrace/1828869 to your computer and use it in GitHub Desktop.
Save jterrace/1828869 to your computer and use it in GitHub Desktop.
A collection of fuzzy floating point utility functions for Python
import math
def almostEqual(a, b, rtol=1.0000000000000001e-05, atol=1e-08):
"""Checks if the given floats are almost equal. Uses the algorithm
from numpy.allclose."""
return math.fabs(a - b) <= (atol + rtol * math.fabs(b))
def floor(v):
"""Returns the floor of the given number, unless it is equal to its
ceiling (within floating point error)."""
floor = math.floor(v)
if fAlmostEqual(floor+1, v):
return floor+1
return floor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment