我需要在Python中对浮点数进行范围检查的干净方法

3 投票
4 回答
2821 浏览
提问于 2025-04-15 16:49

我在找一种简单的方法来检查Python中浮点数的范围,尤其是当最小值和最大值可能为空的时候。

这里有一段相关的代码:

    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

不过,这段代码完全没法处理tmin或tmax为None的情况(这意味着没有最小值或最大值)。

到目前为止,我能想到的最好方法是:

    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

我一直在想,应该有更好(更简洁、更易读)的方法来写这个。有没有什么想法?

4 个回答

4

首先,我们需要设置一个浮点数的无穷大常量。

INF = float(1e3000)

或者

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

第一种方法在实际使用中可以认为是可移植的;你只需要使用一个非常大的数值,确保它超出了你所使用的平台浮点数类型所能表示的范围。第二种方法是“真正的”可移植,但需要使用Python 2.6或更新的版本。

现在,你的条件可以这样写(注意:只有在 tmintmax 不能为零的情况下!):

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

编辑

我犯了一个粗心的错误,没注意到0.0是 tmintmax 的合法值。感谢Roger Pate的提醒。

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 方法。不过我没有找到它(其实也没去找)。 :)

2

使用atzz的回答中的INF

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

撰写回答