Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with big numbers in Lua

Tags:

lua

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?

like image 594
rsc Avatar asked Jul 23 '17 22:07

rsc


People also ask

What is the largest number in Lua?

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.

How are numbers stored in Lua?

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.

What does hashtag mean in Lua?

# is the lua length operator which works on strings or on table arrays.

How do you make an integer in Lua?

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.


1 Answers

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.

like image 88
Paul Kulchenko Avatar answered Sep 30 '22 15:09

Paul Kulchenko