【问题标题】:Unexpected behavior of numpy.real_if_close compared to numpy.real, numpy.imagnumpy.real_if_close 与 numpy.real、numpy.imag 相比的意外行为
【发布时间】:2020-02-21 16:03:00
【问题描述】:

我正在处理scipy tutorial,我遇到了我不太理解的函数 numpy.real_if_close 的行为:

b = np.array([1+1j, 2+1j, 3+1j, 4+5e-15j])
b
>>>[1.+1.e+00j 2.+1.e+00j 3.+1.e+00j 4.+5.e-15j]

np.real(b)
>>>[1. 2. 3. 4.]
b.real
>>>[1. 2. 3. 4.]

np.imag(b)
>>>[0. 0. 0. 5.]
b.imag
>>>[0. 0. 0. 5.]

np.finfo(float).eps
>>>2.220446049250313e-16

b # <-- to make sure I didn't change b
>>>[1.+1.e+00j 2.+1.e+00j 3.+1.e+00j 4.+5.e-15j]

np.real_if_close(b, tol=1000) # <-- does not perform the approx 4+5e-14j ~= 4
>>>[1.+1.e+00j 2.+1.e+00j 3.+1.e+00j 4.+5.e-15j]
b.real_if_close(tol=1000) # <-- raises an AttributeError
>>>AttributeError: 'numpy.ndarray' object has no attribute 'real_if_close'

np.real_if_close([2.1 + 4e-14j], tol=1000) # <-- example from the tutorial
>>>[2.1]

real_if_closerealimag 的文档中,三个函数的参数以相同的方式描述,因此我对它们对同一对象的不同行为感到有些迷茫。

  • 我在这里假设有什么问题吗?
  • 这是一个值得报告的问题吗?

【问题讨论】:

  • b.imag 的输出看起来不正确。应该是array([1.e+00, 1.e+00, 1.e+00, 5.e-15])

标签: python arrays numpy scipy


【解决方案1】:

函数real_if_close 只会在所有元素的虚部接近于零的情况下将数组转换为实数。

你的b.imag实际上是:

array([1.e+00, 1.e+00, 1.e+00, 5.e-15])

所以前三个元素都是1,还不够接近零……

如果你用一个所有元素的虚部接近于零的数组重复这一点,它会按预期工作:

b = np.array([1+0j, 2+1e-14j, 3-1e-15j, 4+5e-15j])

然后np.real_if_close(b, tol=1000) 返回:

array([1., 2., 3., 4.])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多