使用浮点数或双精度数代替整数
我知道Lua的默认实现仅使用浮点数,从而避免了在选择要使用的数学函数变体之前动态确定数字子类型的问题。
我的问题是——如果我尝试在标准 C99 中将整数模拟为双精度数(或浮点数),是否有一种可靠(且简单)的方法来判断可精确表示的最大值是多少?
我的意思是,如果我使用 64 位浮点数来表示整数,我当然无法表示所有 64 位整数(鸽巢原理适用于此)。我怎样才能知道可表示的最大整数?
(尝试列出所有值并不是解决方案 - 例如,如果我在 64 位架构中使用双精度数,因为我必须列出 2^{64} 数字)
谢谢!
I know that the default implementation of Lua uses floating point numbers only, thus circumventing the problem of dynamically determining the subtype of a number before choosing which variant of math function to use.
My question is -- if I try to emulate integers as doubles (or floats) in standard C99, is there a reliable (and simple) way to tell what is the maximum value representable precisely?
I mean, if I use 64-bit floats to represent integers, I certainly cannot represent all 64-bit integers (the pigeonhole principle applies here). How can I tell the maximum integer that is representable?
(Trying to list all values is not a solution -- if, for example, I'm using doubles in a 64-bit architecture, as I'd have to list 2^{64} numbers)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 64 位双精度数,可表示的最大整数为 253 (9007199254740992);对于 32 位双精度数,可表示的最大整数为 224 (16777216)漂浮。请参阅IEEE 浮点数的维基百科页面上的基数。
在 Lua 中验证这一点非常简单:
如果我们手头没有 IEEE 定义的字段大小,那么只要知道我们对浮点数的设计的了解,我们就可以使用一个简单的循环来确定这些值超过可能的值:
上述代码的输出:
当然,由于浮点精度的工作方式,随着浮点指数变正,64 位双精度数可以表示远大于 264 的数字。 有关双精度浮点的 Wikipedia 页面 描述了:
进一步列出了双精度型可以容纳的绝对最大值该页面下方:0x7feffffffffffffff,计算结果为 (1 + (1 − 2−52)) * 21023,即大约 1.7976931348623157e308。
The maximum ones-representable integer is 253 (9007199254740992) for a 64-bit double and 224 (16777216) for a 32-bit float. See the base digits on the Wikipedia page for IEEE floating point numbers.
Verifying this in Lua is pretty simple:
If we don't have the IEEE-defined field sizes handy, knowing what we know about the design of floating point numbers, we can determine these values using a simple loop over the possible values:
The output of the above code:
Of course, due to the way floating-point precision works, a 64-bit double can represent numbers much larger than 264 as the floating exponent grows positive. The Wikipedia page on double-precision floating-point describes:
The absolute largest value a double can hold is listed further down that page: 0x7fefffffffffffff, which computes to (1 + (1 − 2−52)) * 21023, or roughly 1.7976931348623157e308.
IEEE 浮点维基页面 说:
The IEEE floating point wikipage says:
如果您正在查看 int 到 float 和返回 int 之间的转换,它在我的系统上大约分解为 16,777,217 (double 没有任何问题):
If you're looking at a conversion between int to float and back to int, it breaks down around 16,777,217 on my system (double didn't have any issues):