python不正确的浮点数四舍五入 [英] python incorrect rounding with floating point numbers
本文介绍了python不正确的浮点数四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我期待的是 0.313 而不是 0.312有没有想过为什么会这样,有没有其他方法可以用来获得 0.313?
谢谢
解决方案
Python 3 rounds 根据 IEEE 754 标准,使用 轮到偶方法.
如果您想以不同的方式进行舍入,只需手动实现:
导入数学def my_round(n, ndigits):部分 = n * 10 ** ndigitsdelta = 部分 - 整数(部分)# 总是舍入远离 0"如果δ>=0.5或-0.5<增量 <= 0:部分 = math.ceil(部分)别的:部分 = math.floor(部分)返回部分/(10 ** ndigits)
示例用法:
在 [12]: my_round(0.3125, 3)输出[12]:0.313
<小时>
注意:在python2中舍入总是远离零,而在python3中舍入到偶数.(例如,请参阅 2.7 和 3.3 之间 round
函数文档中的差异).
>>> a = 0.3135
>>> print("%.3f" % a)
0.314
>>> a = 0.3125
>>> print("%.3f" % a)
0.312
>>>
I am expecting 0.313 instead of 0.312 Any thought on why is this, and is there alternative way I can use to get 0.313?
Thanks
解决方案
Python 3 rounds according to the IEEE 754 standard, using a round-to-even approach.
If you want to round in a different way then simply implement it by hand:
import math
def my_round(n, ndigits):
part = n * 10 ** ndigits
delta = part - int(part)
# always round "away from 0"
if delta >= 0.5 or -0.5 < delta <= 0:
part = math.ceil(part)
else:
part = math.floor(part)
return part / (10 ** ndigits)
Example usage:
In [12]: my_round(0.3125, 3)
Out[12]: 0.313
Note: in python2 rounding is always away from zero, while in python3 it rounds to even. (see, for example, the difference in the documentation for the round
function between 2.7 and 3.3).
这篇关于python不正确的浮点数四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文