How are Inf and NaN implemented?

跟風遠走 提交于 2019-11-29 06:32:47

Typically, the floating point arithmetic is implemented directly by hardware. There are indeed special bit patterns for infinity and NaN, which are recognized by the hardware floating-point unit.

IEEE 64-bit floating-point numbers, the kind used in CPython on typical systems, have 1 bit for the sign, 11 bits for the exponent, and 52 bits for the mantissa. See https://en.wikipedia.org/wiki/Double-precision_floating-point_format

If the exponent contains 0b11111111111 (all ones), then the number is either inf or nan, depending on what is stored in the mantissa. Python does not need to do anything special to handle these cases. You will get the same results whether you compare the numbers in Python, C, Java, or assembly language.

johan d.

Those are not python-specific behavior, it's rather the floating-point standard Python use (and possibly all common languages?).

nan and inf are special value of the IEEE_754 floating point standard. They have internal representations (the bit sequence you mention) of course, but their behavior is not usual. The behavior is not usual wrt other floats values, but it is well defined by IEEE_754. Implementation is handled at instruction level. (The processor handle this in its floating-point unit circuitry)

One specified and not trivial behavior, NaN != everything, including itself.

Knowing that, you can write something like:

def isNaN(f): return f != f
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!