运行以下代码时:
from platform import python_version
print(python_version())
import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
x[1,:] = x[1,:] / 5
print(x)
y = np.array([1,2,3])
y = y / 5
print(y)
我得到以下输出:
3.8.6
[[1 2 3]
[0 1 1]
[7 8 9]]
[0.2 0.4 0.6]
为什么 numpy/python 在用标量除矩阵中的行时使用整数除法,而使用常规除法除单行?我认为 numpy 3 中的“/”除法总是规则的?
最佳答案
Why does numpy / python use integer division when dividing a row in a matrix by a scalar
事实并非如此 - 您所看到的症状是由于分配造成的。
>>> x = np.array([[1,2,3],[4,5,6],[7,8,9]])
除以整数会生成 float 数组,
>>> z = x[1,:] / 5
>>> z
array([0.8, 1. , 1.2])
但是将该数组分配给整数数组的切片会导致数据类型转换。
>>> x[1,:] = z
>>> x
array([[1, 2, 3],
[0, 1, 1],
[7, 8, 9]])
>>> z.dtype
dtype('float64')
>>> x.dtype
dtype('int32')
>>>
文档中提到了这一点 - Assigning values to indexed arrays
Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints):
关于Python 3 numpy 在矩阵上使用整数除法,在向量上使用常规除法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65168843/