26

What's the difference between:

Math.pow ( x,y ); // x^y

To:

x^y; // x^y

?

Will I prefer to use x^y with double type numbers? Or shell I have to use always with Math.pow() method?

4 Answers 4

44

^ is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow.

3
  • So for example if I want to calc radius from (x,y), I need to: Math.sqrt(Math.pow(x,2)+Math.pow(y,2)) ; ??? thnx
    – Master C
    Commented Apr 23, 2011 at 10:28
  • @Master C: If you want to raise a number to a particular power, you want to use Math.pow. Commented Apr 23, 2011 at 10:29
  • 1
    @Master C: Besides that it's just the distance from the origin in 2d (there's no concept of a radius of a point), I think in this special case Math.sqrt(x*x+y*y) is more readable.
    – Axel
    Commented Apr 23, 2011 at 15:50
12

Additionally for what was said, if you want integer powers of two, then 1 << x (or 1L << x) is a faster way to calculate 2x than Math.pow(2,x) or a multiplication loop, and is guaranteed to give you an int (or long) result.

It only uses the lowest 5 (or 6) bits of x (i.e. x & 31 (or x & 63)), though, shifting between 0 and 31 (or 63) bits.

5

In Java x ^ y is an XOR operation.

4

x^y is not "x to the power of y". It's "x XOR y".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.