Reputation: 520
Today I came across a peculiar behavior of Math.pow(). I am not able to understand the output of the following java code:
long N1 = 999999999999999999L;
System.out.println("N1 : " + N1);
long N2 = (long) Math.pow(N1, 1);
System.out.println("N2 : " + N2);
I get the following output:
N1 : 999999999999999999
N2 : 1000000000000000000
I always thought that Math.pow() produces the exact result as long as the parameters passed to it are integers or longs provided there is no overflow (which is true in this case).
Upvotes: 4
Views: 1935
Reputation: 240908
because it casts long
to double
System.out.println((double)999999999999999999L);
outputs:
1.0E18
and
System.out.println((long)(double)999999999999999999L);
outputs:
1000000000000000000
Upvotes: 10
Reputation: 7345
You can use BigDecimal
for such calculations and not lose precision in converting between types:
BigDecimal b = new BigDecimal(999999999999999999L);
BigDecimal pow = b.pow(1);
Upvotes: 0