I need a clean approach for floating range checks in Python

I am looking for an easy way to check float ranges in Python, where the minimum and maximum borders can be null.

This code:

    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 does not completely allow us to handle the case when tmin or tmax is None (which should be interpreted as meaning that there is no minimum or maximum value).

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 that there should be a better (cleaner, more readable) way to write this. Any ideas?

+3
source share
4 answers

Using INF from atzz answer

if tmin is None: tmin = -INF
if tmax is None: tmax = +INF

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

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

# Neither solution was within the acceptable range.
return None
+2
source

Firstly, some tweaking: we need a constant constant float.

INF = float(1e3000)

or

INF = float('inf')  # Python 2.6+

; - , , . "" , Python 2.6 .

(edit: tmin tmax !):

if (tmin or -INF) <= tval <= (tmax or +INF) :
    return tval

Edit: , , 0.0 tmin tmax. , . , , , ...

+4

, , :

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

, inrange -, . ( ).:)

+4

Using INF from atzz answer (in a way that won't work if used 0.0):

def coalesce(*values):
  for v in values:
    if v is not None:
      return v

if coalesce(tmin, -INF) <= tval <= coalesce(tmax, INF):
  return tval

However, you have clear enough for me:

if ((tmin is None or tmin <= tval) and
    (tmax is None or tval <= tmax)):
   return tval
+3
source

Source: https://habr.com/ru/post/1725154/


All Articles