0

I am trying to solve a mathematical problem in geeksforgeeks wherein I have to calculate the 15 raised to the power 15.

long result = (long)Math.pow(a, b);

Here a,b = 15 Why the above expression evaluates to 437893890380859392 when it should be 437893890380859375

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Tanya Sah
  • 151
  • 1
  • 1
  • 8
  • 2
    Because floating point. Math.pow returns a `double`. – Robert Harvey Dec 28 '18 at 16:00
  • Take a look at the range of the data type returned by Math.pow and see if it can hold the result you expect. I use wolframalpha.com for a convenient tool for large calculations that might exceed the capacity of Java – nicomp Dec 28 '18 at 16:00
  • Why are you casting it to `long`? Math.pow returns a `double`. – Nicholas K Dec 28 '18 at 16:01
  • Your type cast comes too late! Math.pow has already completed and overflowed. – nicomp Dec 28 '18 at 16:01
  • Floating point is an approximation: a finite sum of powers of 2. Huge doubles will increase by more than 1 between adjacent double values. – Joop Eggen Dec 28 '18 at 16:02
  • @nicomp: That doesn't look like an overflow to me. All of the digits are the same except the last two. It's simply a small loss of precision. – Robert Harvey Dec 28 '18 at 16:02

1 Answers1

3

Better use BigInteger, it can handle even bigger values :

BigInteger bigInteger = new BigInteger("15").pow(15);    
System.out.println(bigInteger);
Schidu Luca
  • 3,897
  • 1
  • 12
  • 27