gpt4 book ai didi

python - Numpy 创建 2 的幂数组

转载 作者:行者123 更新时间:2023-12-01 02:32:28 25 4
gpt4 key购买 nike

我尝试过:

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

得到了

>>> 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 肯定不是 2 的 31 次方,之后的答案肯定不是零!
检查我尝试过的某种溢出错误:

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

得到:

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

the rest the same

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

最佳答案

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

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

关于python - Numpy 创建 2 的幂数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46653659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com