How to limit a number in Lua while maintaining accuracy?

Original post:

I need to multiply two 64-bit numbers, but Lua loses accuracy with large numbers. (for example, 9999999999999999999 is shown as 100000000000000000) After multiplication, I need a 64-bit solution , so I need a way to limit the solution to 64 bits. (I know if the solution would be accurate, I could just use% 0x10000000000000000, so that would work too)

EDIT: With Lua 5.3 support and the new 64-bit integer support, this problem no longer exists. Well maintained.

+4
source share
2 answers

Lua uses double precision floating points for all mathematical calculations, including integer arithmetic (see http://lua-users.org/wiki/FloatingPoint ). This gives you about 53 bits of accuracy, which (as you noticed) is less than what you need.

There are several ways to improve accuracy in Lua. It is best to find the most proactive such efforts and discard them. In this case, your question has already been answered; check What is the standard (or best) large number library (arbitrary precision) for Lua?

If your Lua distribution has packages for it, the easy answer is lmapm .

+3
source

If you use LuaJIT instead of Lua, you get access to all the built-in types of C99, including long long , which is usually 64 bits.

 local ffi = require 'ffi' -- Needed to parse constants that do not fit in a double: ffi.cdef 'long long strtoll(const char *restrict str, char **restrict endptr, int base);' local a = ffi.C.strtoll("99999999999999999", nil, 10) print(a) print(a * a) 

=> 3803012203950112769LL (provided that the result is truncated to 64 bits)

+1
source

Source: https://habr.com/ru/post/1443052/


All Articles