Java指数误差为2 ^ 31次幂

AJH*_*ker 1 java

我正在编写一个java程序来输出2的指数幂(顺便说一下,我不能使用Math.pow()),但是在2 ^ 31和2 ^ 32我得到了别的东西.另外,我不打算接受负整数.

我的代码:

class PrintPowersOf2 {
    public static void main (String[] args) {
        printPowersOf2(10);
        printPowersOf2(5);
        printPowersOf2(2);
        printPowersOf2(-5);
        printPowersOf2(30);
        printPowersOf2(32);
    }

    public static void printPowersOf2 (int x) {
        for(int i=0;i<x+1;i++) {
            int y = exponent (i);
            System.out.print(y);
            if(!(i == x)) {
                System.out.print(" ");
            }
        }
        System.out.println();
    }

    static int exponent(int power) {
        int output = 1; 
        for (int z=0; z<power; z++) 
        output *= 2; 
        return output; 
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

1 2 4 8 16 32 64 128 256 512 1024
1 2 4 8 16 32
1 2 4

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648 0
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 7

An int用32位表示.因此-2^31,2^31-1可以表示和之间的任何值.没有超出这个范围.

您可以使用long(64位)或a BigInteger(可以表示所有数字达到内存限制的数据结构).

使用这些结构(尤其是BigInteger)的缺点是CPU并不总是提供算术指令.因此,添加两个BigInteger实例比使用int或更多时间需要更多时间long.在a的情况下long,如果CPU是32位,则至少需要两条指令来处理它.


在旁注.CPU提供了一种更好的方法来计算两种功能:移位操作.

你可以简单地写:

long value = 0x01L << power;//power of two, all in one simple instruction.
Run Code Online (Sandbox Code Playgroud)

其工作方式如下:移位向左移动位.因此,如果原始值是:

  0001 1011 << 2
= 0110 1100
Run Code Online (Sandbox Code Playgroud)

以二进制表示向左移位在算术上与乘以2相同.