Multiplication vs ^ operator vs Math.pow () for integer degrees

I was wondering how the power in Java and the performance of the available methods are calculated. So I wrote a simple test to test the operations of Math.pow() , * and ^ .

 public static void main(String[] args) { int SIZE = 100000000; int[] arr1 = new int[SIZE]; long st1, end1, st2, end2, st3, end3; st1 = System.currentTimeMillis(); for (int i = 0; i < SIZE; i++) { arr1[i] = (int) Math.pow(i, 4); } end1 = System.currentTimeMillis(); System.out.println("pow: " + (end1 - st1)); arr1 = new int[SIZE]; st2 = System.currentTimeMillis(); for (int i = 0; i < SIZE; i++) { arr1[i] = i * i * i * i; } end2 = System.currentTimeMillis(); System.out.println("mul: " + (end2 - st2)); arr1 = new int[SIZE]; st3 = System.currentTimeMillis(); for (int i = 0; i < SIZE; i++) { arr1[i] = i^4; } end3 = System.currentTimeMillis(); System.out.println(" ^: " + (end3 - st3)); //to prevent optimizations form skipping the calculations for (int i = 0; i < SIZE; i++) { if (arr1[i] == 1){ System.out.println(1); } } System.out.println("done"); } 

and if the first two results were expected:

 pow: 19253 19128 19205 19145 19185 19130 19162 19177 19191 19157 | 19173 mul: 91 86 91 85 98 90 90 105 87 95 | 92 ^: 80 85 80 70 60 65 75 60 70 60 | 71 

the third is a bit confusing. Why is ^ always a little faster than simple multiplication, and which one should I use?

All tests were performed with JRE 1.7 under similar conditions.

0
source share
2 answers

The ^ operator does not perform exponentiation - it is a bitwise "exclusive OR" (aka "xor").

Using integer math for 100,000,000 raised to fourth power will give incorrect results - a 32-bit integer cannot store large numbers.

Math.pow() will use floating point arithmetic. Answers may be 100% inaccurate due to accuracy errors, but should be able to display the desired range of results.

To get 100% accurate values ​​for large numbers, you should use the BigInteger class. However, this will not be particularly fast. This is a trade-off that you must make when considering accuracy and performance.

+9
source

The ^ operator in Java is a bitwise exclusive OR and is definitely not like a force function.

Link

+4
source

All Articles