Reputation: 364
first, sorry about my bad English...
today i tried to check if Integer.MAX_VALUE*Integer.MAX_VALUE
System.out.println("long*long= "+Long.MAX_VALUE*Long.MAX_VALUE);
System.out.println("int*int= "+Integer.MAX_VALUE*Integer.MAX_VALUE);
System.out.println("double*double= "+Double.MAX_VALUE*Double.MAX_VALUE);
System.out.println("float*float= "+Float.MAX_VALUE*Float.MAX_VALUE);
System.out.println("short*short= "+Short.MAX_VALUE*Short.MAX_VALUE);
the results:
long*long= 1
int*int= 1
double*double= Infinity
float*float= Infinity
short*short= 1073676289
why is that? if float^2=Infinity, so long^2 should also be Infinity... and 1 is clearly a mistake... anyone have any idea? tnx
Upvotes: 0
Views: 151
Reputation: 899
Because 2^63 -1 * 2^63 -1 is not infinite, you need a variable that can store the answer of this equation. the default call is unable to print it but it has answer. which is reflected by true(1)
Upvotes: 0
Reputation: 31290
For seeing how integers multiply, use the binary notation. For simplicity's sake I use a 4 bit signed integer (where the MAX is 7), but the principle is the same for byte, short, int and long.
0111 x 0111
----
0111
0111
0111
-------
110001
The columns from right to left:
1) 1 => 1
2) 1+1 => 10 => 0 and carry 1c into 3)
3) 1+1+1+1c => 100 => 0 and carry 1c into 5) (sic! 5)
4) 1+1 => 10 => 0 and carry 1c into 5)
5) 1+1c+1c => 11
Higher order bits are irrelevant because truncated.
This isn't even a peculiarity of Java - it is the consequence of two's complement arithmetic modulo^(number of bits).
Upvotes: 2
Reputation: 18964
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.1 says
If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format.
Your integer answers are too large to fit in the result type, so the high-order bits of the true answer are simnply discarded.
(2^n-1) * (2^n -1) is 2^2n - 2*2^n + 1, which is 1 modulo 2^n - so you are getting the expected answer.
The rules for floating point types are different.
Upvotes: 3
Reputation: 500227
long^2 should also be Infinity
Only floating-point types have a special value for infinity. Integer types do not; this includes long
.
Long.MAX_VALUE * Long.MAX_VALUE
evaluates to 1
is due to integer overflow, since ((2**63 -1) ** 2) mod (2**64) == 1
(Wolfram Alpha).
Upvotes: 2