Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java's Math.pow round off the result?

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).

like image 442
scv Avatar asked Dec 25 '22 00:12

scv


1 Answers

because it casts long to double

System.out.println((double)999999999999999999L);

outputs:

1.0E18

and

System.out.println((long)(double)999999999999999999L);

outputs:

1000000000000000000
  • why is that ?
like image 108
jmj Avatar answered Dec 28 '22 10:12

jmj