【问题标题】:Numpy.linalg.det() returns incorrect resultNumpy.linalg.det() 返回不正确的结果
【发布时间】:2014-12-06 02:06:18
【问题描述】:

有人知道为什么 Numpy 返回“-2.0000000000000004”而不是“-2”

>>> M = [[1,2],[3,4]]
>>> numpy.linalg.det(M)
-2.0000000000000004

我正在使用 Python 3.4.2 (x64)、Numpy 1.9.1 和 Windows 7 x64。

【问题讨论】:

  • 归功于floating numbers。我不会担心的。它相当自然。
  • @Marcin 在 Numpy 文档中一切正常 - docs.scipy.org/doc/numpy/reference/generated/… numpy.linalg.det() 函数返回 -2.0 如果计算像 a=1*4-3*2 这样的数组的行列式,我获取 int 值 a=-2
  • @Natasha:阅读 Marcin 链接的教程(或 3.x version,几乎相同)。 -2.0000000000000004-2 相差一点点,所以这只是无意义的舍入错误。
  • 他们可能将打印精度设置为 1 或 2,例如np.set_printoptions(precision=2)。或者在 Ipython 中:%precision %0.2f
  • 现在一切都清楚了,谢谢同志们! :-*

标签: python windows python-3.x numpy runtime-error


【解决方案1】:

使用round 和第二个参数作为2(或根据需要)

例子:

M = [[1,2],[3,4]]

print (  numpy.linalg.det(M)  )          # -2.0000000000000004

print (  round(numpy.linalg.det(M),2)  ) # -2.0

【讨论】:

    猜你喜欢
    • 2012-04-11
    • 2016-02-06
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2014-11-03
    • 2021-10-07
    相关资源
    最近更新 更多