Python default formatting when floating point formatting

I am trying to solve some floating point problems in my code in Python 2.7.10. When testing, I came across strange behavior using the method format:

print "{}".format(0.3000000000004) # 13 decimals

Fingerprints: 0.3

But:

print "{}".format(0.300000000004) # 12 decimals

Fingerprints: 0.300000000004

Since I do not indicate the format, why is it around the first number? Is there a default number of decimal places allowed?

+6
source share
2 answers

, . format. Python 2 12 ( , ) float.__str__, :

>>> str(0.3000000000004) # unlike str(0.3000000000014) -> '0.300000000001'
'0.3'

format_spec :f 6:

>>> '{:f}'.format(0.3000000000004)
'0.300000' 

repr, :

>>> '{!r}'.format(0.3000000000004)
'0.3000000000004'

Python 3 , :

>>> str(0.3000000000004)
'0.3000000000004'

float float_repr Python 3 ( float_str):

(reprfunc)float_repr,                       /* tp_repr */
...
(reprfunc)float_repr,                        /* tp_str */

Python2.7 float_str float_repr __str__ __repr__ :

(reprfunc)float_repr,                       /* tp_repr */
...
(reprfunc)float_str,                        /* tp_str */

, , , 12d.p. PyFloat_STR_PRECISION ( Python 2):

#define PyFloat_STR_PRECISION 12

float, 12 .

+10

, python ( ) . 0,3. , : http://0.30000000000000004.com/

( ), :

print "{}".format("0.3000000000004")

:

print "0.3000000000004"
-2

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


All Articles