我需要一种干净的方法来检查Python中的范围检查浮点数
发布时间:2020-12-20 12:25:24 所属栏目:Python 来源:网络整理
导读:我正在寻找一种在 Python中使用范围检查浮点数的简单方法,其中最小和最大边界可能为空. 有问题的代码是: tval = float(-b - discriminant) / float (2*a) if tval = tmin and tval = tmax: return tval tval = float(-b + discriminant) / float (2*a) if t
我正在寻找一种在
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 我一直认为必须有更好的(更清晰,更可读)的方式来编写它.有任何想法吗? 解决方法
使用来自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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |