【问题标题】:Numpy Arange generating values of inconsistent decimal pointsNumpy Arange 生成不一致小数点的值
【发布时间】:2019-08-01 10:24:40
【问题描述】:

谁能解释一下这里发生了什么?

为什么 0.3 和 0.7 的值有更多的小数点。 我只想要 1 个小数点值。

threshold_range = np.arange(0.1,1,0.1)
threshold_range.tolist()
[Output]: [0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7000000000000001, 0.8, 0.9]

【问题讨论】:

标签: python python-3.x numpy data-science


【解决方案1】:

使用np.round

例如

import numpy as np

threshold_range = np.arange(0.1,1,0.1)
print(threshold_range.tolist())
print(np.round(threshold_range, 2).tolist())

O/P:

[0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7000000000000001, 0.8, 0.9]
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

【讨论】:

  • 谢谢。但我很好奇它为什么会这样。既然你给了一个解决方案来解决它,我会把它标记为答案。至于为什么,@tnknepp 在 cmets 中回答了。
  • @Saed see this Python/numpy 浮点文本精度行为。
【解决方案2】:

解决方案:您可以简单地使用 round 函数:

threshold_range = np.arange(0.1,1,0.1).round(1)
threshold_range.tolist() # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

错误原因:我认为它与浮点精度有关;)

【讨论】:

  • 感谢您的回答。我必须将上面的一个标记为答案,因为这是第一个响应(就像你的一样):)
猜你喜欢
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多