Problem with floating point precision
John Roth
newsgroups at jhrothjr.com
Tue Aug 17 12:19:50 EDT 2004
"j_mckitrick" <j_mckitrick at bigfoot.com> wrote in message
news:ec6dce8b.0408170538.1f0211d2 at posting.google.com...
> I checked the docs, but found nothing about floating point issues.
>
> I am working on an app that deals with currency values, and only does
> addition and subtraction (no division). But I am starting to see
> values that should be the same failing a compare! What is the
> workaround or correct way to compare 2 floats? It worked fine for
> months, then suddenly starting acting odd. I might have upgraded
> Python somewhere in between, I can't recall.
The basic issue here is that you shouldn't be using floats
for currency. Granted, lots of people do, but it will eventually
run into exactly the problem you're describing.
The reason is that currency is best handled by some form of
arithmetic that works with discrete quantities, while floats are
intended to be used with continuous quantities (like scientific
and engineering measurements).
There's a floating decimal package in 2.4 that is intended
to eventually (in 2.5 maybe?) be the base of a currency
package. However, that doesn't help today.
What I'd do is create a currency class that uses plain
old, boring ints as the base, with the necessary decimal
point handling present behind the scene.
John Roth
>
> jonathon
More information about the Python-list
mailing list