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?
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). :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With