Precision issue
Michael Hudson
mwh at python.net
Fri Oct 10 07:41:07 EDT 2003
Duncan Booth <duncan at NOSPAMrcp.co.uk> writes:
> 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'?
I believe "computational and code complexity" is the main answer to
that one.
Start here
http://citeseer.nj.nec.com/gay90correctly.html
?
> 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.
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...
Cheers,
mwh
--
34. The string is a stark data structure and everywhere it is
passed there is much duplication of process. It is a perfect
vehicle for hiding information.
-- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html
More information about the Python-list
mailing list