What is the best way to compare floats for almost-equality in Python?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands
--
Chapters
00:00 What Is The Best Way To Compare Floats For Almost-Equality In Python?
00:23 Answer 1 Score 112
00:34 Answer 2 Score 19
00:57 Answer 3 Score 77
01:22 Accepted Answer Score 529
02:04 Thank you
--
Full question
https://stackoverflow.com/questions/5595...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #floatingpoint
#avk47
ACCEPTED ANSWER
Score 529
Python 3.5 adds the math.isclose and cmath.isclose functions as described in PEP 485.
If you're using an earlier version of Python, the equivalent function is given in the documentation.
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
rel_tol is a relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference between them while still considering them equal.
abs_tol is an absolute tolerance that is applied as-is in all cases. If the difference is less than either of those tolerances, the values are considered equal.
ANSWER 2
Score 112
Something as simple as the following may be good enough:
return abs(f1 - f2) <= allowed_error
ANSWER 3
Score 77
I would agree that Gareth's answer is probably most appropriate as a lightweight function/solution.
But I thought it would be helpful to note that if you are using NumPy or are considering it, there is a packaged function for this.
numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
A little disclaimer though: installing NumPy can be a non-trivial experience depending on your platform.
ANSWER 4
Score 19
Use Python's decimal module, which provides the Decimal class.
From the comments:
It is worth noting that if you're doing math-heavy work and you don't absolutely need the precision from decimal, this can really bog things down. Floats are way, way faster to deal with, but imprecise. Decimals are extremely precise but slow.