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?
^
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
.
Math.pow
.
Commented
Apr 23, 2011 at 10:29
Math.sqrt(x*x+y*y)
is more readable.
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.