Floating point behavior in Python 2.6 vs 2.7

后端 未结 1 988
野性不改
野性不改 2021-01-21 00:47

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         


        
相关标签:
1条回答
  • 2021-01-21 01:02

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

    0 讨论(0)
提交回复
热议问题