Floating point behavior in Python 2.6 vs 2.7

So, I exit the Python 2.6 interpreter, and I get the following:

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, as shown 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 would like to ask why this is happening, and how can I get Python 2.6 to behave like 2.7?

+3
source share
1 answer

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

The C source code for float.__str__() formats the floating point value using the g formatter code into the sprintf() function with an accuracy of 12 positions.

To get the same result in Python 2.6, you 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 view has changed, not the actual values. Floating-point values ​​are still binary approximations of real numbers, and binary fractions do not always coincide with the exact number.

If you need higher accuracy than the float approximations you are proposing, you need to switch to using the decimal.Decimal() provides accuracy at the expense of speed (floating-point arithmetic is processed by hardware on modern computers).

+10
source

Source: https://habr.com/ru/post/1261545/


All Articles