简体   繁体   English

Python 2.6与2.7中的浮点行为

[英]Floating point behavior in Python 2.6 vs 2.7

So I break out the Python 2.6 interpreter and I get this: 所以我打破了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

However in Python 2.7 I get more human-like results like below: 但是在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
>>> 

I 'd like to ask why is this happening and how could I possibly make Python 2.6 behave like 2.7? 我想问为什么会发生这种情况,我怎么可能让Python 2.6表现得像2.7?

The float.__repr__() and float.__str__() methods in Python 2.7 changed; Python 2.7中的float.__repr__()float.__str__()方法已更改; the Python 3.1 float-to-string conversion method was backported and values are now rounded. Python 3.1 float-to-string转换方法被反向移植,现在值已四舍五入。

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. float.__str__()的C源代码使用g格式化程序代码将浮点值格式化为sprintf()函数,精度为12个位置。

To get the same result in Python 2.6, you'll have to format the string yourself: 要在Python 2.6中获得相同的结果,您必须自己格式化字符串:

'%.12g' % fp_value

or use the format() function: 或使用format()函数:

format(fp_value, '.12g')

Note that in Python 2.7 only the representation changed, not the actual values. 请注意,在Python 2.7中,只更改了表示 ,而不是实际值。 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. 如果需要比float近似提供的精度更高,则需要切换到使用decimal.Decimal()类型 This maintains precision, at the cost of speed (floating point arithmetic is handled in hardware on modern computers). 这样可以以速度为代价保持精度(浮点运算在现代计算机上的硬件中处理)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM