Python中的round()似乎无法正确舍入

时间:2020-03-05 18:51:33  来源:igfitidea点击:

round()函数的文档指出,我们向其传递了一个数字,并将小数点后的位置进行了舍入。因此,它应该这样做:

n = 5.59
round(n, 1) # 5.6

但是,实际上,老的浮点怪异现象不断蔓延,我们会得到:

5.5999999999999996

出于UI的目的,我需要显示5.6。我在Internet上闲逛,发现一些文档取决于我对Python的实现。不幸的是,这在我的Windows开发机和我尝试过的每台Linux服务器上都会发生。另请参阅此处。

除了创建自己的回合库之外,还有什么办法可以解决这个问题?

解决方案

回答

关于什么:

round(n,1)+epsilon

回答

无法帮助存储,但至少格式化正确:

'%.1f' % round(n, 1) # gives you '5.6'

回答

我们可以将数据类型切换为整数:

>>> n = 5.59
>>> int(n * 10) / 10.0
5.5
>>> int(n * 10 + 0.5) 
56

然后通过插入语言环境的小数点分隔符来显示数字。

但是,吉米的答案更好。

回答

我们可以使用字符串格式运算符,类似于sprintf。

mystring = "%.2f" % 5.5999

回答

如果我们执行str(round(n,1))而不是round(n,1),则会得到'5.6'。

回答

浮点数学运算容易出现轻微但令人讨厌的精度误差。如果可以使用整数或者定点,则可以保证精度。

回答

打印吸盘。

print '%.1f' % 5.59  # returns 5.6

回答

格式化无需四舍五入即可正确进行:

"%.1f" % n

回答

round(5.59,1)运行正常。问题在于5.6无法精确地用二进制浮点表示。

>>> 5.6
5.5999999999999996
>>>

正如Vinko所说,我们可以使用字符串格式对显示进行四舍五入。

如果需要,Python有一个用于十进制算术的模块。

回答

看一下Decimal模块

Decimal “is based on a floating-point
  model which was designed with people
  in mind, and necessarily has a
  paramount guiding principle –
  computers must provide an arithmetic
  that works in the same way as the
  arithmetic that people learn at
  school.” – excerpt from the decimal
  arithmetic specification.

Decimal numbers can be represented
  exactly. In contrast, numbers like 1.1
  and 2.2 do not have an exact
  representations in binary floating
  point. End users typically would not
  expect 1.1 +  2.2 to display as
  3.3000000000000003  as it does with binary floating point.

Decimal提供了一种操作类型,可以轻松编写需要浮点运算的应用程序,并且还需要以人类可读的格式(例如会计)显示这些结果。