Precision issue

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Oct 10 09:55:34 EDT 2003


Ben Finney <bignose-hates-spam at and-benfinney-does-too.id.au> wrote in 
news:slrnbodbq6.2fj.bignose-hates-spam at rose.localdomain.fake:

> On Fri, 10 Oct 2003 10:36:16 +0000 (UTC), Duncan Booth wrote:
>> I know this is an FAQ, but the one thing I've never seen explained
>> satisfactorily is why repr(3.4) has to be '3.3999999999999999' rather
>> than '3.4'?
> 
> Because '3.4' is what str(3.4) returns.  If repr(3.4) lies about the
> value stored, what function will you leave us to discover the actual
> value?

In what way is 3.3999999999999999 any more the value than 3.4?

>>> print 3.3999999999999999 == 3.4
True

The exact value stored is neither of these, it is somewhere in between the 
two (perhaps 3.399999999999999911182158029987476766109466552734375 if I 
counted it right). repr gives a representation of the float which is 
guaranteed to convert back to the same sequence of bits, 3.4 will do just 
as well for this case as the longer value.

Try a different value, say 3.333*30. Repr gives you 99.990000000000009, str 
gives you 99.99. I'm not proposing that should change because 
99.990000000000009 != 99.99.

> The str() function is for getting the working output of the value.  The
> repr() function is for discovering, as precisely as possible, the actual
> value.

It doesn't do that. It currently shows you the value to sufficient 
precision to allow you to reconstruct the bits exactly.

Documentation on repr:
repr(...)
    repr(object) -> string
    
    Return the canonical string representation of the object.
    For most object types, eval(repr(object)) == object.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list