Numpy创建2的幂数组

时间:2021-04-27 21:24:50

I tried :

我试过了 :

>>>a = np.array(2**np.arange(42)[::-1],dtype = np.uint64)

and got

>>> a
array([                   0,                    0,                    0,
                          0,                    0,                    0,
                          0,                    0,                    0,
                          0, 18446744071562067968,           1073741824,
                  536870912,            268435456,            134217728,
                   67108864,             33554432,             16777216,
                    8388608,              4194304,              2097152,
                    1048576,               524288,               262144,
                     131072,                65536,                32768,
                      16384,                 8192,                 4096,
                       2048,                 1024,                  512,
                        256,                  128,                   64,
                         32,                   16,                    8,
                          4,                    2,                    1], dtype=uint64)

18446744071562067968 is certainly not 2 to the power 31 and after that the answers are certainly not zero!
to check for some kind of overflow error I tried :

18446744071562067968肯定不是2的力量31,之后答案肯定不是零!检查我试过的某种溢出错误:

>>> a[0] = 2**42

and got:

>>> a
array([       4398046511104, ..... 

  the rest the same  

Can anybody tell me what has gone wrong?

谁能告诉我出了什么问题?

1 个解决方案

#1


1  

Yes, np.arange(42) is defaulting to a signed integer, likely np.int32, probably because you are on a 32-bit architecture or you are on Windows. Ditch the np.array wrapper, which is totally useless, and pass the dtype to np.arange:

是的,np.arange(42)默认为有符号整数,可能是np.int32,可能是因为您使用的是32位架构,或者您使用的是Windows。抛弃np.array包装器,它完全没用,并将dtype传递给np.arange:

2**np.arange(42, dtype = np.uint64)[::-1]

#1


1  

Yes, np.arange(42) is defaulting to a signed integer, likely np.int32, probably because you are on a 32-bit architecture or you are on Windows. Ditch the np.array wrapper, which is totally useless, and pass the dtype to np.arange:

是的,np.arange(42)默认为有符号整数,可能是np.int32,可能是因为您使用的是32位架构,或者您使用的是Windows。抛弃np.array包装器,它完全没用,并将dtype传递给np.arange:

2**np.arange(42, dtype = np.uint64)[::-1]