格式化浮点数时Python格式默认舍入 [英] Python format default rounding when formatting float number
问题描述
我试图在Python 2.7.10中的代码中解决一些浮点问题。在测试时,我遇到了一个奇怪的行为,使用格式
方法:
I'm trying to solve some floating-point problems in my code in Python 2.7.10. When testing I've encountered a strange behaviour with the format
method:
print "{}".format(0.3000000000004) # 13 decimals
打印: 0.3
但是:
But:
print "{}".format(0.300000000004) # 12 decimals
打印: 0.300000000004
因为我没有指定格式,为什么它是第一个数字?是否有一个允许的小数位数的默认值?
Since I'm not specifying the format, why does it round the first number? Is there a default number of allowed decimal places?
推荐答案
由于您没有指定格式,用过的。所以这对于 format
并不是一个问题。对于 float .__ str __
,Python 2截断为12个字符的精度(不包括前导零),在截断之后,所有尾随零都被清除:
Since you do not specify a format, the default type coercion to string is used. So this isn't really an issue with format
. Python 2 truncates to a precision of 12 characters (excluding the leading zero, if any) for float.__str__
, and after truncation in this case, all trailing zeros are cleaned up:
>>> str(0.3000000000004) # unlike str(0.3000000000014) -> '0.300000000001'
'0.3'
添加 format_spec
:f
给你的默认精度为6:
Adding the format_spec
:f
gives you the default precision of 6:
>>> '{:f}'.format(0.3000000000004)
'0.300000'
指定宽度和精度或使用 repr
来获得一个很好的表示形式:
Specify the width and precision or use repr
to get a good representation:
>>> '{!r}'.format(0.3000000000004)
'0.3000000000004'
不同于Python 3:
The behavior is different in Python 3 though:
>>> str(0.3000000000004)
'0.3000000000004'
浮动的格式只能通过一个函数来处理 <$ c在Python 3中它没有特殊的code> float_str
(reprfunc)float_repr, /* tp_repr */
...
(reprfunc)float_repr, /* tp_str */
而Python2.7定义了一个单独的处理程序 float_str
和 float_repr
for __str __
和 __ repr __
分别为:
whereas Python2.7 defines a separate handler float_str
and float_repr
for __str__
and __repr__
respectively:
(reprfunc)float_repr, /* tp_repr */
...
(reprfunc)float_str, /* tp_str */
这里的决定性变量我认为是超出12d.p精度损失的原因。 PyFloat_STR_PRECISION
(在Python 2中定义):
The deciding variable here which I think is the reason for the precision loss beyond 12d.p. is PyFloat_STR_PRECISION
(defined in Python 2):
#define PyFloat_STR_PRECISION 12
在默认转换中,浮点数超过12个字符的浮点数将被截断。
It reverses to a truncation for floats taking more than 12 characters in the default conversion.
这篇关于格式化浮点数时Python格式默认舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!