Result Java Math.pow completes the result?

Today I came across a peculiar behavior of Math.pow (). I can not 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 () gives the exact result if the parameters passed to it are integer or long, if there is no overflow (which is true in this case).

+4
source share
2 answers

because he drops longindouble

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

outputs:

1.0E18

and

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

outputs:

1000000000000000000
+10
source

You can use BigDecimalfor such calculations and not lose the accuracy of conversion between types:

BigDecimal b = new BigDecimal(999999999999999999L);
BigDecimal pow = b.pow(1);
0
source

Source: https://habr.com/ru/post/1569234/


All Articles