【问题标题】:How to solve representation errors with floating-point numbers in Python?如何解决 Python 中浮点数的表示错误?
【发布时间】:2018-09-18 01:18:25
【问题描述】:

我需要在不四舍五入的情况下截断百分之一的小数。 我用的是方法:

y = 78.459

x = int(y * 100) / 100

返回为78.45。应该的。

但是,如果我这样做了

y = 5.10

x = int(y * 100) / 100

它返回为5.09,而它应该是5.10

我知道这是一个表示错误,由于 Python 中的浮点数不准确,但我不知道如何修复它。 如果有人可以帮助我弄清楚如何修复表示错误,或者找到一种更好的方法来截断百分之一,我将不胜感激。 谢谢

【问题讨论】:

标签: python floating-point truncation


【解决方案1】:

为此使用decimal 模块:

>>> from decimal import Decimal as d
>>> y = d('5.10')
>>> x = int(y * 100) / 100
>>> x
5.1
>>> 

【讨论】:

  • 这并不是 Decimal 的正确用法。
  • @StephenRauch 真的吗?那么最好的是什么
  • 好的,谢谢。我可以将值从 input() 传递给 d() 吗?
  • @Hollyleaf25 你是什么意思?
  • 如果 x = input("输入一个数字:") 那么我可以做 y = d(x) 吗?
【解决方案2】:

您可以在decimal 模块中使用quantize function

>>> import decimal
>>> y = decimal.Decimal('78.459')
>>> z = decimal.Decimal('.01')
>>> y.quantize(z, rounding=decimal.ROUND_DOWN)
Decimal('78.45')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2017-12-17
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多