如何将Python除以-0.0和0.0分别导致-Inf和Inf? [英] How to get Python division by -0.0 and 0.0 to result in -Inf and Inf, respectively?
问题描述
我遇到的情况是合理的除以0.0或除以-0.0,我希望分别看到+ Inf和-Inf作为结果.看来Python很喜欢抛出
I have a situation where it is reasonable to have a division by 0.0 or by -0.0 where I would expect to see +Inf and -Inf, respectively, as results. It seems that Python enjoys throwing a
ZeroDivisionError: float division by zero
在任何情况下
.显然,我认为我可以将其封装为0.0来进行测试.但是,我找不到区分+0.0和-0.0的方法. (仅供参考,您可以通过输入-0.0或通过常见的计算方式(例如-1.0 * 0.0)轻松获得-0.0.
in either case. Obviously, I figured that I could simply wrap this with a test for 0.0. However, I can't find a way to distinguish between +0.0 and -0.0. (FYI you can easily get a -0.0 by typing it or via common calculations such as -1.0 * 0.0).
IEEE可以很好地处理所有这些问题,但是Python似乎很努力地隐藏经过深思熟虑的IEEE行为.实际上,0.0 == -0.0实际上是IEEE的功能,因此Python的行为会严重破坏事情.它可以在C,Java,Tcl甚至JavaScript上完美运行.
IEEE handles this all very nicely, but Python seems to take pains to hide the well thought out IEEE behavior. In fact, the fact that 0.0 == -0.0 is actually an IEEE feature so Python's behavior seriously breaks things. It works perfectly well in C, Java, Tcl, and even JavaScript.
建议?
推荐答案
from math import copysign
def divide(numerator, denominator):
if denominator == 0.0:
return copysign(float('inf'), denominator)
return numerator / denominator
>>> divide(1, -0.0)
-inf
>>> divide(1, 0)
inf
这篇关于如何将Python除以-0.0和0.0分别导致-Inf和Inf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!