【问题标题】:numpy array float number division leads to strange behaviornumpy 数组浮点数除法导致奇怪的行为
【发布时间】:2017-12-07 05:31:03
【问题描述】:

请按照以下代码行:

A = np.array([0 for i in range(10)])

A[:] = 0.1/2

A

Out[36]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

A[:] = float(0.2/2)

A[:]

Out[38]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

我不明白,为什么 numpy 会出现这种奇怪的行为?

我正在使用 numpy 1.13.3

【问题讨论】:

  • 在初始化后检查 A 的 dtype。

标签: python python-3.x list numpy floating-accuracy


【解决方案1】:

因为当你定义你的数组时,它是dtype=int。将其定义为float,它将按您的预期工作。

示例:

a = np.arange(10) # dtype = int
a[:] = 0.1 # converts to int so to 0
print a

a = np.arange(10.) # dtype = float
# or equivalently a = np.arange(10, dtype=float)
a[:] = 0.1 # works as you expect
print a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 2013-02-07
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2020-01-14
    • 2018-03-12
    相关资源
    最近更新 更多