Java results differ for (int)Math.pow(2,x) and 1<<x

前端 未结 5 1928
忘掉有多难
忘掉有多难 2020-12-31 17:21

Why do the following two operations yield different results in Java for x = 31 or 32 but the same results for x=3?

int         


        
5条回答
  •  甜味超标
    2020-12-31 17:36

    Here's a micro-benchmark for the case of a long. On my laptop (2.8GHz), using shift instead of Math.pow is over 7x faster.

    int limit = 50_000_000;
    @Test
    public void testPower() {
        Random r = new Random(7);
        long t = System.currentTimeMillis();
        for (int i = 0; i < limit; i++) {
            int p = r.nextInt(63);
            long l = (long)Math.pow(2,p);
        }
        long t1 = System.currentTimeMillis();
        System.out.println((t1-t)/1000.0); // 3.758 s
    }
    @Test
    public void testShift() {
        Random r = new Random(7);
        long t = System.currentTimeMillis();
        for (int i = 0; i < limit; i++) {
            int p = r.nextInt(63);
            long l = 1L << p;
        }
        long t1 = System.currentTimeMillis();
        System.out.println((t1-t)/1000.0); // 0.523 s
    }
    

提交回复
热议问题