Python inequality comparison dealing with floating point precision

200 Views Asked by At

I need to compare floating point numbers with inequalities:

if x >= y:

However, due to floating point precision issues, sometimes this fails when it should succeed (x = 0.21 and y= 0.21000000000000002). I was thinking to create an epsilon:

epsilon = 0.000000001
if x >= y - epsilon:

I'd rather use a standard mechanism for this. Python has a math.isclose function that works for equality, but I couldn't find anything for inequality. So I have to write something like this:

import math

if x > y or math.isclose(x, y):

I have to do this a ton in my application... easy enough, I'll just create a function. My question is if there's a standard way to deal with inequalities and floats? Is there a numpy.greater_or_equal(x, y) type function?

1

There are 1 best solutions below

3
Grismar On

Since you indicated that the overhead of a function call is not really an issue, why not simply provide:

def greater_than_or_close(x: float, y: float) -> bool:
    from math import isclose
    return x > y or isclose(x, y)

You can import that wherever you need it.

Your comments stated: "This seems like one of those functions that I can get wrong easily due to surprising floating point precision issues", but since this only relies on x actually being greater than y, or using the math.isclose() function, that risks seems to be absent?

(or rather, keeping the import outside the function:)

import math


def greater_than_or_close(x: float, y: float) -> bool:
    return x > y or math.isclose(x, y)