Hello world
If I try to divide 14 billion by two I get this result:
14000000000/2;
557549056.0
Two problems: the answer is wrong; it turns the integer into a float.
Also this function continuously dividing by 10 (which while Iām at it, feels wrong - I wonder is there a simpler way to achieve the same idea?) gives another strange result of 1115098112:
10.collect({|i| 14000000000.div(10.pow(i))});
[ 1115098112, 111509811, 11150981, 1115098, 111509, 11150, 1115, 111, 11, 1 ]
I found this is the integer help file:
Blockquote
NOTE: A 32 bit signed integer can represent values in the range -2147483648 to 2147483647. Adding up further returns in a wrapped result, so that and 2147483647+1= -2147483648. For a larger range, one can use Float, which is 64 bit and supports many (but not all) numerical methods that int does.
Blockquote
So I took the advice and turned the 14 billion into a float:
10.collect({|i| 14000000000.0.div(10.pow(i))});
[ 1115098112, 1400000000, 140000000, 14000000, 1400000, 140000, 14000, 1400, 140, 14 ]
Still a strange result, if almost what I expected. The number 1115098112 appears again.
I would be very grateful if anyone could enlighten me to what exactly is happening with these big numbers!
Many thanks,
Dom