这是我正在重写的在六边形格子上生成点同心环的算法的一部分。
我原以为这都是整数数学,但我发现在某些情况下数组会意外地创建为 float !
在下面的序列中,p0
是 float64
for n=1
但 int64
for n >1
我根本无法弄清楚为什么会这样。
我在 MacOS 上运行 numpy 版本 1.17.3,Anaconda 安装 Python 3.7.3
import numpy as np
n_max = 3
for n in range(1, n_max+1):
seq = np.arange(n, -n-1, -1, dtype=int)
p0 = np.hstack((seq, (n-1)*[-n], seq[::-1], (n-1)*[n]))
print('n: ', n)
print('seq: ', seq)
print('p0: ', p0.dtype, p0)
print('')
返回
n: 1
seq: [ 1 0 -1]
p0: float64 [ 1. 0. -1. -1. 0. 1.]
n: 2
seq: [ 2 1 0 -1 -2]
p0: int64 [ 2 1 0 -1 -2 -2 -2 -1 0 1 2 2]
n: 3
seq: [ 3 2 1 0 -1 -2 -3]
p0: int64 [ 3 2 1 0 -1 -2 -3 -3 -3 -3 -2 -1 0 1 2 3 3 3]
这是预期的行为吗?
更新 1: 好的 np.hstack(([1, 0, -1], 1*[7]))
返回 int64
但是 np.hstack(([1, 0, -1], 0*[7]))
返回 float64
所以它出现了 0* [n]
在 np.hstack
操作的元组中触发向上转换为 float64
。
更新 2: 刚刚在代码审查中提出:Is there a better, cleaner or otherwise “less tricky” way to get these hexagonal arrays of dots arranged in this spiral pattern?
最佳答案
触发整个数组转换为 np.float64
的是 n=0
和 (n-1)*[ n]
和 (n-1)*[-n]
:
print((n-1)*[n])
# []
np.hstack
从每个要连接的输入数组构造一个数组。对于每个数组,都会调用 np.atleast_1d
, 默认情况下将空数组转换为 np.float64
dtype:
np.atleast_1d([])
# array([], dtype=float64)
关于python - 这种对整数进行运算的 numpy 算法偶尔会返回 float ,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61382568/