Lua笔记--number的存储

本文探讨了Lua语言中number类型的存储方式,依据IEEE754标准,揭示了浮点数能够精确表示小于2^53的整数的原因,解决了人们对简单运算可能引入误差的担忧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 253 (approximately 1016 ) 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 253 . In particular, a Lua number can represent any 32-bit integer without rounding problems.

小于 253 的整数都是可以用浮点数精确存储的,所以不存在 1+23 的问题。可为什么小于 253 的整数就可以精确存储呢?这里面需要了解浮点数在计算机内部到底是如何存储的,有一个标准叫IEEE754 ,它规定了浮点数是如何存储的,可以看看我写的对IEEE 754的理解(文末链接) 。

简单地说,双精度浮点数能存储的有效位数最大是53,这里的位数是指化成二进制之后的位数,如果位数大于53,则存在不精确存储。而53位最多可以存储的整数即为 253 ,至于不精确存储具体发生在那些时候,可以参考我写的文章。

对IEEE754标准的理解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值