Java指数误差为2 ^ 31次幂 [英] Java exponent error at 2^31 power
问题描述
我正在编写一个java程序来输出2的指数幂(顺便说一句,我不能使用 Math.pow()
),但是在2 ^ 31和2 ^ 32我得到别的东西。另外,我不打算接受负整数。
I am writing a java program to output exponential powers of 2 (by the way, I cannot use Math.pow()
), however at 2^31 and 2^32 I get something else. Also, I don't intend to accept negative integers.
我的代码:
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;
}
}
我得到的输出是:
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
推荐答案
int
以32位表示。因此,可以表示 -2 ^ 31
和 2 ^ 31-1
之间的任何值。没有超出此范围。
An int
is represented with 32 bits. Thus any value between -2^31
and 2^31-1
can be represented. Nothing out of this range.
您可以使用 long
(64位)或 BigInteger
(一个数据结构,可以表示所有数字,直到内存限制)。
You can use a long
(64 bits), or a BigInteger
(a datastructures that can represented all numbers up to the memory limit).
使用这些结构的缺点(尤其是 BigInteger
)是CPU并不总是提供算术指令。因此,添加两个 BigInteger
实例需要的时间比使用 int
或 long
。如果 long
,如果CPU是32位,则至少需要两条指令来处理它。
The disadvantage of using these structures (especially BigInteger
) is that a CPU does not always offer instructions for arithmetic. Thus adding two BigInteger
instances requires more time than doing this with an int
or long
. In case of a long
, if the CPU is 32-bit, it requires at least two instructions to process this.
在旁注中。 CPU提供了一种更好的方法来计算两个的权限:移位操作。
On a sidenote. A CPU offers a better way to calculate the powers of two: shift operations.
你可以简单地写:
long value = 0x01L << power;//power of two, all in one simple instruction.
这样做如下:一个班次向左移动位。因此,如果原始值是:
This works as follow: a shift moves bits to the left. Thus if the original value is:
0001 1011 << 2
= 0110 1100
以二进制表示向左移位与算术相同乘以2。
Shifting to the left in a binary representation is arithmetically the same as multiplying with two.
这篇关于Java指数误差为2 ^ 31次幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!