Multiplication vs ^ operator vs Math.pow() for int

2019-09-03 09:18发布

I got curious about the way power calculation is done in Java and the performance of available methods. So I wrote a simple test to check on Math.pow(), * and ^ operations.

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 quite 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 one is a bit confusing. How come ^ is always a bit faster than simple multiplication and which one should be used?

All the tests were run with JRE 1.7 in similar conditions.

标签: java pow
2条回答
来,给爷笑一个
2楼-- · 2019-09-03 09:50

the ^ operator in Java is bitwise exclusive OR and definitaly not similiar to the power function.

Reference

查看更多
再贱就再见
3楼-- · 2019-09-03 10:04

The ^ operator is not performing exponentiation - it's a bitwise "exclusive OR" (aka "xor").

Using integer math for 100000000 raised to the fourth power will give incorrect results - a 32-bit integer cannot store numbers that large.

Math.pow() will use floating point arithmetic. The answers may not be 100% accurate due to precision issues, but should be capable of representing the required range of results.

To get 100% accurate values for numbers that large, you should use the BigInteger class. However it will not be particularly fast. This is a trade off you have to make when considering accuracy vs performance.

查看更多
登录 后发表回答