rounding errors?
Grant Edwards
grante at visi.com
Sat Jul 3 01:16:49 EDT 2004
todd wrote:
> I've just started using Python, and am having an extraordinary
> experience.
Python's pretty cool, eh?
> One thing worries me, however, I'm planning on doing some
> mathematical research with Python, and it appears that it does
> funny thing with floating point numbers.
No, it isn't. The problem is that you're expecting it to do
something funny with them and it isn't.
> Maybe It's superficial,
No, on the contrary, it's quite fundamental to the way floating
point works in computers.
> but here's what I'm getting,using the interpreter..
>
>>>>>>.31
>>>
>>> 0.31
>>>
>>>>>>.32
>>>
>>> 0.32000000000000001
[...]
And you'd prefer that the intrepreter lied to you and printed
"0.32" when you tell it to print the number 0.3200..001 --
that's a common reaction from people who don't understand
floating point numbers. If you want, you can specify a format
when printing floating point numbers so that you only see as
many digits as you want to:
>>> "%0.2f" % 0.32
'0.32'
>>>
> Now, I realize that this is really small errors.. Does anybody
> have an explanation why Python picks up or loses these?
Somebody else has already posted a pointer to the Python FAQ
about floating point, but if you're planning on doing numerical
research using floating point on computers, you really ought to
take a class on numerical methods or numerical analysis using
floating point on computers.
--
Grant Edwards grante Yow! PIZZA!!
at
visi.com
More information about the Python-list
mailing list