Dict handling of floats

Tim Peters tim_one at email.msn.com
Fri Apr 25 01:37:40 EDT 2003


[Donn Cave, on float displays]
> ...
> You're looking at the repr() output, which for reasons we won't
> go into here renders the value to its ultimate precision.  If
> you run the same numbers through str(), they'll look different.
>
> Maybe the big question here is whether your notion of "right"
> has any computational significance, that is, does it matter to
> your application which of these renditions more accurately
> describes the value.  Because in that respect, repr is right
> and str is almost right.

Nope, it's very rare for either to tell you the whole truth.  repr()
produces the minimal number of digits so that non-equal floats never have
equal reprs, but that's usually a fraction of the number of decimal digits
that would be needed to display the true value stored in the machine.  For
example, as explained in the oft-referenced Tutorial Appendix, in

>>> 0.1
0.10000000000000001
>>>

the 17-digit repr is still just an approximation to the value in the
machine, which latter is exactly

0.1000000000000000055511151231257827021181583404541015625

repr() rounds that to 17 significant digits, because 17 is the smallest
number of digits you can round back to in all cases without producing
identical strings for some non-equal floats.  It's also the smallest number
you can round back to and always get back the same float you started with if
you read the string in again.  Telling the whole truth wasn't a goal here;
telling enough of the truth to avoid gross surprises was.  That "0.1" isn't
exactly one-tenth is a gross surprise inherited from the hardware, of
course.






More information about the Python-list mailing list