为什么Python的回合如此奇怪? [英] Why is Python's round so strange?

查看:79
本文介绍了为什么Python的回合如此奇怪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

  #!/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?

推荐答案

看看

注意 round()对于浮点的行为可能令人惊讶:例如,round(2.675, 2)给出的是2.67而不是预期的 2.68.这不是错误:这是因为大多数十进制数 分数不能完全表示为浮点数.请参见 浮动 点算术:问题和局限性 以获取更多信息.

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.

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

If you keep digging (i.e. click that link), you'll find an example similar to yours:

内置round()函数的文档指出 四舍五入为最接近的值,四舍五入为零.自从 小数部分2.675恰好位于2.672.68之间, 您可能期望这里的结果是(二进制近似值) 2.68.并非如此,因为当十进制字符串2.675被转换时 转换为二进制浮点数,然后再次替换为二进制 近似值,其确切值为

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

字符串格式也无法解决您的问题.浮点数只是没有按照您期望的方式存储:

String formatting won't fix your problem either. The floating point number just isn't stored the way you'd expect it to be:

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

这并不是一个真正的修复程序",但是Python确实有一个decimal模块,该模块专门用于浮点运算:

This isn't really a "fix", but Python does have a decimal module, which is designed for floating point arithmetic:

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

这篇关于为什么Python的回合如此奇怪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆