lausent
lausent

Reputation: 325

Which is the fastest way to compare two float value in python?

I have two float value ("a" and "b") in Python 3 and each float value can have from 5 to 15 decimal point. The problem is that when two value are equal for me, python return me a False.

Examples:
a=12.091824733909107, b=12.091824733909117
or also
a=12.54678, b=12.5467800000123

For me in the above examples "a" and "b" are equal. One solution is to use round(a, 5) and round(b,5) to cut decimal point but use round() million of time increase the time process. Is there another solution that not require to use round()?

Upvotes: 0

Views: 7020

Answers (1)

Copperfield
Copperfield

Reputation: 8520

you need to set a tolerance range, such that if the difference between a and b is bellow they are considered equals

>>> def is_close(a, b, tol=1e-9):
        return abs(a-b) <= tol

>>> is_close(12.091824733909107, 12.091824733909117)
True
>>> is_close(12.54678, 12.5467800000123)
True
>>> 

or in python 3.5+

>>> import math
>>> math.isclose(12.091824733909107, 12.091824733909117)
True
>>> math.isclose(12.54678, 12.5467800000123)
True
>>> 

Upvotes: 3

Related Questions