【问题标题】:Python integer and float multiplication errorPython整数和浮点乘法错误
【发布时间】:2021-06-15 05:27:00
【问题描述】:

这个问题似乎很愚蠢,但我无法正确回答。输出 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]]

【问题讨论】:

  • empy_like 匹配 cm0 dtype (int)。如果你想要浮动,请不要使用它。

标签: python numpy integer multiplication


【解决方案1】:

empty_like() matches the type 默认为给定的 numpy 数组,正如 cmets 中建议的 hpaulj。在您的情况下,cm0 是整数类型。

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

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

converting to integers 时,Python 还会在小数点处截断浮点数。在您的情况下,每次乘法都会产生一个介于1.890.36 之间的数字,因此将结果取底将分别产生0s 和1s。

【讨论】:

  • 感谢大家的快速回复,感谢!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2023-03-25
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多