Lua 笔记--number的存储
Lua语言里面的数字类型是number,没有像C/C++里面那样多种多样,如果是这样的话,那么在计算机内数字就应该是按照浮点数存储的,而浮点数存储不是有不确定性吗?不会出现类似1+2=2.9999999999的错误吗?
这个问题在Roberto Ierusalimschy的《Programming In Lua》一书中进行了说明
Some people fear that even a simple increment or comparison can go weird with floating-point numbers. Reality, however, is not like that. Virtually all plat-forms nowadays follow the IEEE 754 standard for floating-point representation.Following this standard, the only possible source of errors is a representation error, which happens when a number cannot be exactly represented. An operation rounds its result only if that result has no exact representation. Any operation with a result that has an exact representation must give that exact result.
The fact is that any integer up to $2^{53}$ (approximately $10^{16}$ ) has an exact representation as a double-precision floating-point number. When you use a double to represent an integer, there is no rounding error at all, unless the number has an absolute value greater than $2^{53}$ . In particular, a Lua number can represent any 32-bit integer without rounding problems.
小于$2{53}$的整数都是可以用浮点数精确存储的,所以不存在$1+2\neq3$的问题。可为什么小于$2{53}$的整数就可以精确存储呢?这里面需要了解浮点数在计算机内部到底是如何存储的,有一个标准叫IEEE754 ,它规定了浮点数是如何存储的,可以看看我写的对IEEE 754的理解(文末链接) 。
简单地说,双精度浮点数能存储的有效位数最大是53,这里的位数是指化成二进制之后的位数,如果位数大于53,则存在不精确存储。而53位最多可以存储的整数即为$2^{53}$ ,至于不精确存储具体发生在那些时候,可以参考本人写的文章。
网友评论