Inf和NaN如何实施? [英] How are Inf and NaN implemented?

查看:74
本文介绍了Inf和NaN如何实施?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为数学概念,我很清楚infnan实际上是什么.但是我真正感兴趣的是它们如何以编程语言实现.

As mathematical concepts, I am well aware of what inf and nan actually are. But what I am really interested in is how they are implemented in programming languages.

在python中,我可以在算术表达式和条件表达式中使用infnan,例如:

In python, I can use inf and nan in arithmetic and conditional expressions, like this:

>>> nan = float('nan')
>>> inf = float('inf')
>>> 1 + inf
inf
>>> inf + inf
inf
>>> inf - inf
nan

这会让我相信python内部对于这两个数学量具有特殊的保留位序列,并且没有其他数字可以假定这些位置.我的假设正确吗?您能在这方面启发我吗?

This would lead me to believe that python internally has a special reserved bit sequence for these two mathematical quantities, and no other number can assume these positions. Is my assumption correct? Can you please enlighten me in this regard?

如果我的假设是正确的,那么这很容易解释:

If my assumption is correct, then this can be explained easily:

>>> inf == inf
True

但是,这不是:

>>> nan == nan
False

显然,在数学上,这是正确的答案.但是python如何知道在这种情况下应该吐出False呢?

Obviously, in mathematics, this is the right answer. But how does python know that it should spit out False in this instance?

此外,python的实现与java或c ++的实现有何不同?

Furthermore, how does python's implementation differ from that of java or c++?

推荐答案

通常,浮点算法由硬件直接实现.的确,对于无限和NaN,确实存在特殊的位模式,这些位模式已由硬件浮点单元识别.

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位浮点数(在典型系统中CPython中使用的那种数字)的符号为1位,指数为11位,尾数为52位.参见 https://en.wikipedia.org/wiki/Double-precision_floating-point_format

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

如果指数包含0b11111111111(全为1),则数字为inf或nan,具体取决于尾数中存储的内容. Python不需要做任何特殊的事情来处理这些情况.无论您比较Python,C,Java还是汇编语言中的数字,您都将获得相同的结果.

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.

这篇关于Inf和NaN如何实施?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆