3
System.out.println(Math.pow(16, 0.5)); is 4.0

and

System.out.println(Math.pow(16, (1/2)));  is 1.0

Why??? I need to use fraction!

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Apetrei Ionut
  • 293
  • 4
  • 12
  • When you believe you have found a bug in one of the standard libraries, you have to ask yourself "why has nobody else found such a fundamental bug in such a commonly used library?" That in turn will lead you to the realization that perhaps the bug isn't in the library, after all. This realization has helped me to find my own bugs many times. Currently, one of my co-workers believes he has found a bug in Oracle's database. As we don't yet understand the problem, I can't prove him wrong. But I'm willing to bet €100 to his €1 that the bug isn't in Oracle's code. – Breandán Dalton Dec 18 '14 at 09:21

1 Answers1

11

1/2 is 0, due to integer division, so Math.pow(16, (1/2) is Math.pow(16, 0), which is 1.0.

In order for 1/2 to be evaluated using floating point division, you have to cast either 1 or 2 to double :

System.out.println(Math.pow(16, ((double)1/2)));

Or use double literal in the first place :

System.out.println(Math.pow(16, (1.0/2)));

or

System.out.println(Math.pow(16, (1/2.0)));
Eran
  • 387,369
  • 54
  • 702
  • 768