Python整数和浮点数乘法错误

Python integer and float multiplication error

这个问题看起来很假,但我答不对。输出 cm1 应该是浮点数,但我只得到零和一。

import numpy as np
import scipy.spatial.distance
sim  = scipy.spatial.distance.cosine
a = [2, 3, 1]
b = [3, 1, 2]
c = [1, 2, 6]
cm0 = np.array([a,b,c])
ca, cb, cc = 0.9, 0.7, 0.4 
cr = np.array([ca, cb, cc])
cm1 = np.empty_like(cm0)
for i in range(3):
    for j in range(3):
        cm1[i,j] = cm0[i,j] * cr[i] * cr[j]
print(cm1)

我得到:

[[1 1 0]
 [1 0 0]
 [0 0 0]]

正如@hpaulj 在评论部分所说,问题是使用 empty_like 将保留 cm0 dtype,解决它尝试:

cm1 = np.empty_like(cm0, dtype=float)

empty_like() matches the type of the given numpy array by default, as hpaulj 在评论中建议。在你的情况下 cm0 是整数类型。

empty_like 函数接受多个参数,其中之一是 dtype。将 dtype 设置为 float 应该可以解决问题:

cm1 = np.empty_like(cm0, dtype=float)

并且 Python 在 converting to integers 时在小数点处截断浮点数。在您的情况下,每次乘法都会产生 1.890.36 之间的数字,因此对结果进行取整将分别导致 0s 和 1s。