To see how repr(x)
works for float in CPython, I checked the source code for float_repr
:
buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
'r', 0,
Py_DTSF_ADD_DOT_0,
NULL);
This calls PyOS_double_to_string
with format code 'r'
which seems to be translated to format code 'g'
with precision set to 17:
precision = 17;
format_code = 'g';
So I'd expect repr(x)
and f'{x:.17g}'
to return the same representation. However this doesn't seem to be the case:
>>> repr(1.1)
'1.1'
>>> f'{1.1:.17g}'
'1.1000000000000001'
>>>
>>> repr(1.225)
'1.225'
>>> f'{1.225:.17g}'
'1.2250000000000001'
I understand that repr
only needs to return as many digits as are necessary to reconstruct the exact same object as represented in memory and hence '1.1'
is obviously sufficient to get back 1.1
but I'd like to know how (or why) this differs from the (internally used) .17g
formatting option.
(Python 3.7.3)