Loss Of Precision Float In Python
Solution 1:
You are confusing string presentation with actual contents. Nowhere is precision lost, only the string produced to write to your console is using a rounded value rather than show you all digits. And always remember that float numbers are digital approximations, not precise values.
Python floats are formatted differently when using the str()
and repr()
functions; in a list or other container, repr()
is used, but print it directly and str()
is used.
If you don't like either option, format it explicitly with the format()
function and specifying a precision:
printformat(maxState, '.12f')
to print it with 8 decimals, for example.
Demo:
>>>maxState = -34.67875545008369>>>repr(maxState)
'-34.67875545008369'
>>>str(maxState)
'-34.6787554501'
>>>format(maxState, '.8f')
'-34.67875545'
>>>format(maxState, '.12f')
'-34.678755450084'
The repr()
output is roughly equivalent to using '.17g'
as the format, while str()
is equivalent to '.12g'
; here the precision denotes when to use scientific notation (e
) and when to display in floating point notation (f
).
I say roughly because the repr()
output aims to give you round-trippable output; see the change notes for Python 3.1 on float()
representation, which where backported to Python 2.7:
What is new is how the number gets displayed. Formerly, Python used a simple approach. The value of
repr(1.1)
was computed asformat(1.1, '.17g')
which evaluated to'1.1000000000000001'
. The advantage of using 17 digits was that it relied on IEEE-754 guarantees to assure thateval(repr(1.1))
would round-trip exactly to its original value. The disadvantage is that many people found the output to be confusing (mistaking intrinsic limitations of binary floating point representation as being a problem with Python itself).The new algorithm for
repr(1.1)
is smarter and returns'1.1'
. Effectively, it searches all equivalent string representations (ones that get stored with the same underlying float value) and returns the shortest representation.
Post a Comment for "Loss Of Precision Float In Python"