Can be doubled to represent a 64-bit number without loss of precision

I want to use lua (which internally uses only doubles) to represent an integer that cannot have rounding errors from 0 to 2 ^ 64-1, or something terrible will happen.

Can this be done?

+6
c double floating-point lua
source share
8 answers

Not

To represent the exponent (binary point position), at least a few bits of a 64-bit double must be used, and therefore less than 64 bits are available for the actual number. Thus, no, a 64-bit double cannot represent all the values ​​that a 64-bit integer can use (and vice versa).

+14
source share

Despite the fact that you received good answers to your question about 64-bit types, you may still need a practical solution to your specific problem. The most reliable solution I know is to build Lua 5.1 with the LNUM patch (also known as the Lua integer patch), which can be downloaded from LuaForge. If you do not plan to create Lua from a C source, there is at least one pure Lua library that processes 64-bit signed integers - see Lua Wikis.

+5
source share

Double is a 64-bit type. However, you lose 1 bit for the sign and 11 for the exponent.

So the answer is no: it is impossible.

+4
source share

From memory, double can accurately represent a signed 53-bit integer.

+3
source share

No, you cannot use Double to store 64-bit integers without loss of precision.

However, you can apply the Lua patch, which adds support for true 64-bit integers to the Lua interpreter. Apply the LNUM patch to your Lua source and recompile.

+2
source share

On 64 bits you can only store 2 ^ 64 different codes. This means that the 64-bit type, which can represent 2 ^ 64 integers, has no place to represent anything else, such as floating point numbers.

Obviously, double can represent many non-integer numbers, so it cannot match your requirements.

+1
source share

IEEE 754 double cannot accurately represent 64-bit integers. It can, however, represent exactly every 32-bit integer value.

0
source share

I don't know anything about lua
but if you could understand how to perform bitwise manipulation of a float in this language, theoretically you could make a wrapper class that took your number as a string and set the float bits in the order that represents the number you gave it
a more practical solution would be to use the bignum library

-one
source share

All Articles