Precision issue

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Oct 10 06:36:16 EDT 2003


Alex Martelli <aleax at aleax.it> wrote in
news:8lvhb.258000$R32.8375967 at news2.tin.it: 

> Ladvánszky Károly wrote:
> 
>> Entering 3.4 in Python yields 3.3999999999999999.
>> I know it is due to the fact that 3.4 can not be precisely expressed
>> by the powers of 2. Can the float handling rules of the underlying
>> layers be set from Python so that 3.4 yield 3.4?
> 
> It seems, from the question, that you might not have entirely
> understood and grasped the explanations you can find at:
> http://www.python.org/doc/current/tut/node14.html
> and I quote, in particular:

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

Surely the important thing is that the equality eval(repr(x))==x has to 
hold for floating point numbers, and that holds just as true for the short 
3.4 as it does for the 17 digit version? 

Microsoft .Net has a numeric format "R" which does a similar job. The R 
specifier guarantees that a floating point numeric value converted to a 
string will be parsed back into the same numeric value. It does this by 
first trying a general format with 15 digits of precision then parsing that 
back to a number. If the result is not the same as the original it then 
falls back to the 17 digit value. There's no reason why Python couldn't do 
the same:

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.

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