python - 为什么Python的round这么奇怪?

标签 python floating-point rounding

我的代码:

  #!/usr/bin/python
  # -*- coding: utf-8 -*-
  print (round(1.555, 1))  # It seems normal
  print (round(1.555, 2))  # Why it is not output 1.56?
  print (round(1.556, 2))  # It seems normal

输出:

  sam@sam:~/code/python$ ./t2.py
  1.6
  1.55
  1.56
  sam@sam:~/code/python$

round(1.555, 1) 输出 1.6

为什么 round(1.555, 2) 不输出 1.56

最佳答案

看看the documentation :

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

如果您继续挖掘(即单击该链接),您会发现一个与您的示例类似的示例:

The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero. Since the decimal fraction 2.675 is exactly halfway between 2.67 and 2.68, you might expect the result here to be (a binary approximation to) 2.68. It’s not, because when the decimal string 2.675 is converted to a binary floating-point number, it’s again replaced with a binary approximation, whose exact value is

2.67499999999999982236431605997495353221893310546875

字符串格式化也不能解决您的问题。 float 并没有按照您期望的方式存储:

>>> '{:0.2f}'.format(1.555)
'1.55'

这并不是真正的“修复”,但 Python 确实有一个 decimal 模块,它是为浮点运算而设计的:

>>> from decimal import Decimal
>>> n = Decimal('1.555')
>>> round(n, 2)
Decimal('1.56')

关于python - 为什么Python的round这么奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14249971/

相关文章:

python - Tkinter 不与 Pycharm 配合使用

python - 在post_save信号django中捕获logentry历史

python-3.x - 如何将浮点转换为任何浮点的 XE-Y 表示

c++ - 使用等式比较 float 的情况

bash - 在 bash 中四舍五入

java - 尝试使用 thrift 的 TFileTransport 和 TFileProcessor 让 Python 客户端与 Java 服务器对话

math - 为什么十进制数不能用二进制精确表示?

java - RoundingMode HALF_UP 无法正常工作

r - summary() 舍入

python - 迭代 Pandas Dataframe 中的日期以获取每周不同列的计数