Precision issue

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Oct 10 08:09:15 EDT 2003


Michael Hudson <mwh at python.net> wrote in
news:7h3r81lb9u6.fsf at pc150.maths.bris.ac.uk: 

>> 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'?
> 
> I believe "computational and code complexity" is the main answer to
> that one.
> 
> Start here
> 
>     http://citeseer.nj.nec.com/gay90correctly.html
<snip>

The code I gave isn't exactly complex, even when you rewrite it in C.

>> def float_repr(x):
>>      s = "%.15g" % x
>>      if float(s)==x: return s
>>      return "%.17g" % x
>> 
>> This would be MUCH friendlier for newcomers to the language.
> 
> It would be nice, but I think it's pretty hard to do efficiently.  Tim
> Peters would be more certain than me :-)
> 
> "Patches welcome" might apply, too.  I don't think your suggested
> float repr will fly, I'm afraid...
> 
I'm happy to do a patch if there is any chance of it being accepted. 
Obviously doing the conversion twice makes the code slower, but I'm not 
sure how critical it would be given that its a pretty fast operation to 
begin with:

C:\Pythonsrc\python\dist\src\PCbuild>python ..\lib\timeit.py "repr(3.4)"
100000 loops, best of 3: 10.5 usec per loop

C:\Pythonsrc\python\dist\src\PCbuild>\python23\python ..\lib\timeit.py 
"repr(3.4)"
100000 loops, best of 3: 7.58 usec per loop

So its about a third slower, but you have to do 300,000 reprs before you 
lose 1 second of cpu time. 

-- 
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