I am in need to store a large number in Lua, for example the number 63680997318088143281752740767766707563546963464218564507450892460763521488675430192536461.
If I simple assign to a variable, I don't get the actual number:
local n = 63680997318088143281752740767766707563546963464218564507450892460763521488675430192536461
print(string.format("%.0f",n)) -- prints 63680997318088143929455344863959288468423333130904105158115881995380577784972357899649024
What would be the possible turn arounds to handle large numbers?
as compiled by default, the Number is a double , on most compilers that's an IEEE 64-bit floating point. that means 10bit exponent, so the maximum number is roughly 2^1024, or 5.6e300 years.
Lua numbers are stored as floating point (doubles) internally, not integers; thus while they can represent incredibly large numbers, above 2^53 they lose integral precision — they can't represent every whole integer value.
# is the lua length operator which works on strings or on table arrays.
Lua has no integer type, as it does not need it. There is a widespread misconception about floating-point arithmetic errors and some people fear that even a simple increment can go weird with floating-point numbers.
Lua numbers have limited precision, but you are trying to store a number that exceeds what can be stored. You'll need to use a different mechanism to store them and operate on these numbers.
The key words are "bignum" and "arbitrary precision numbers". Quick google search returns several pure-Lua modules (bignum and lua-nums) and one C-based one (lmapm). Also see this SO answer for other options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With