Python 2.6中的浮点行为与2.7 [英] Floating point behavior in Python 2.6 vs 2.7

查看:187
本文介绍了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
输入help,copyright,credits或license 了解更多信息。
>>> 2.1
2.1000000000000001
>>> 2.2
2.2000000000000002
>>> 2.2
2.2000000000000002

然而,在Python 2.7中,我得到了更像人类的结果,如下所示: / b>

  Python 2.7.5+(默认,2013年9月19日,13:48:49)
[GCC 4.8.1 ] on linux2
输入help,copyright,credits或license以获取更多信息。
>>> 5.4
5.4
>>> 1.1
1.1
>>> 0.2
0.2
>>>

我想问为什么会发生这种情况,我怎么可能让Python 2.6的行为像2.7 float .__ repr __()和<$ c $ 在Python 2.7中改变了c> float .__ str __()方法; Python 3.1的float-to-string转换方法被反向移植,并且值被四舍五入。
$ b

的源代码float .__ str __()使用 g 格式程序代码将一个浮点值格式化为 sprintf()函数精确到12位。

为了在Python 2.6中得到相同的结果,你必须自己格式化字符串:

 '%。12g'%fp_value 

或使用 format()函数:

$ p $格式(fp_value,'请注意,在Python 2.7中,只有表示发生了改变,不是实际值。浮点值仍然是实数的二进制近似值,而二进制小数并不总是与表示的精确值相加。

如果你需要比 float >近似值提供的精度更高,您需要切换到使用 decimal.Decimal()键入。这保持了精度,代价是速度(现代计算机上的浮点算法是用硬件处理的)。

So I break out the Python 2.6 interpreter and I get this:

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

However in Python 2.7 I get more human-like results like below:

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
>>> 

I 'd like to ask why is this happening and how could I possibly make Python 2.6 behave like 2.7?

解决方案

The float.__repr__() and float.__str__() methods in Python 2.7 changed; the Python 3.1 float-to-string conversion method was backported and values are now rounded.

The C source code for float.__str__() formats a floating point value using the g formatter code to the sprintf() function, with a precision of 12 positions.

To get the same result in Python 2.6, you'll have to format the string yourself:

'%.12g' % fp_value

or use the format() function:

format(fp_value, '.12g')

Note that in Python 2.7 only the representation changed, not the actual values. Floating point values are still binary approximations of real numbers, and binary fractions don't always add up to the exact number represented.

If you need to have more precision than what float approximations offer you, you need to switch to using the decimal.Decimal() type instead. This maintains precision, at the cost of speed (floating point arithmetic is handled in hardware on modern computers).

这篇关于Python 2.6中的浮点行为与2.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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