编程语言
首页 > 编程语言> > Python 2.6与2.7中的浮点行为

Python 2.6与2.7中的浮点行为

作者:互联网

所以我打破了Python 2.6解释器,我得到了这个:

Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2.1
2.1000000000000001
>>> 2.2
2.2000000000000002
>>> 2.2
2.2000000000000002

但是在Python 2.7中,我得到了更像人类的结果,如下所示:

Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 5.4
5.4
>>> 1.1
1.1
>>> 0.2
0.2
>>> 

我想问为什么会发生这种情况,我怎么可能让Python 2.6表现得像2.7?

解决方法:

Python 2.7中的float .__ repr __()和float .__ str __()方法已更改; Python 3.1 float-to-string转换方法被反向移植,现在值已四舍五入.

float .__ str __()的C源代码使用g格式化程序代码将浮点值格式化为sprintf()函数,精度为12个位置.

要在Python 2.6中获得相同的结果,您必须自己格式化字符串:

'%.12g' % fp_value

或使用format()函数:

format(fp_value, '.12g')

请注意,在Python 2.7中,只更改了表示,而不是实际值.浮点值仍然是实数的二进制近似值,二进制分数并不总是加起来表示的确切数字.

如果您需要比浮动近似为您提供更高的精度,则需要切换到使用decimal.Decimal() type.这样可以以速度为代价保持精度(浮点运算在现代计算机上的硬件中处理).

标签:python,floating-point,floating-accuracy,python-2-7,python-2-6
来源: https://codeday.me/bug/20190718/1491741.html