Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need a clean approach for range-checking floats in Python

Tags:

python

I'm looking for a simple way of range checking floats in Python where the minimum and maximum bounds may be null.

The code in question is:

    tval = float(-b - discriminant) / float (2*a)
    if tval >= tmin and tval <= tmax:
        return tval 

    tval = float(-b + discriminant) / float (2*a)
    if tval >= tmin and tval <= tmax:
        return tval

    # Neither solution was within the acceptable range.
    return None

However, this completely fails to handle the case where tmin or tmax is None (which should be interpreted to mean that there is no minimum or maximum respectively).

So far the best I've been able to come up with is:

    tval = float(-b - discriminant) / float (2*a)
    if (tmin == None or tval >= tmin) and (tmax == None or tval <= tmax):
        return tval 

    tval = float(-b + discriminant) / float (2*a)
    if (tmin == None or tval >= tmin) and (tmax == None or tval <= tmax):
        return tval

    # Neither solution was within the acceptable range.
    return None

I keep thinking there has to be a better (cleaner, more readable) way to write that. Any ideas?

like image 725
Adam Luchjenbroers Avatar asked Jun 25 '26 23:06

Adam Luchjenbroers


1 Answers

Maybe I'd define a checker function first, for readability:

def inrange(x, min, max):
    return (min is None or min <= x) and (max is None or max >= x)

tval = float(-b - discriminant) / float (2*a)
if inrange(tval, tmin, tmax):
    return tval 

tval = float(-b + discriminant) / float (2*a)
if inrange(tval, tmin, tmax):
    return tval 

# Neither solution was within the acceptable range.
return None

There must be a module defining such an inrange method somewhere, I bet. But I did not find it (nor look for it, though). :)

like image 110
Johannes Charra Avatar answered Jun 27 '26 11:06

Johannes Charra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!