[Python-Dev] The Case Against Floating Point ==

Imri Goldberg lorgandon at gmail.com
Thu Mar 13 09:20:48 CET 2008


Heya
I've been using Python for development for some years now, but up until 
now, I didn't participate much in work on Python itself. I've decided to 
'take a shot at it', even if a small one at first.

To the subject at hand:
Most experienced programmers know that you shouldn’t compare floating 
point numbers with ==. If you want to check floating point equality, you 
usually decide on a precision, and check either the absolute error, or 
the relative error. Another option is to use the decimal module. Hence, 
floating point == isn’t used, maybe except for rare circumstances. I 
would even venture to say that when possible, static checkers should 
emit warnings on floating point ==.

On the other hand there are the beginner programmers. They usually use 
== by mistake, and will be surprised by the strange results they 
sometimes get back.

My suggestion is to do either of the following:
1. Change floating point == to behave like a valid floating point 
comparison. That means using precision and some error measure.
2. Change floating point == to raise an exception, with an error string 
suggesting using precision comparison, or the decimal module.

Since this change is not backwards compatible, I suggest it be added 
only to Python 3.
Personally, I prefer the second option (== to raise an exception). It is 
clearer, and less confusing.

Arguments against this suggestion are:

1. This change breaks existing programs:
I believe it most likely triggers hidden bugs. Since the suggestion is 
to change it only in Python 3, Those programs will most likely be broken 
by other changes as well, and will need to be changed anyway.

2. This change breaks compatibility with C-like languages:
I agree. However, the already agreed on change of the / operator is even 
a stronger break. Most arguments for changing the / operator apply here 
as well.

3. Programmers will still need the regular ==:
Maybe, and even then, only for very rare cases. For these, a special 
function\method might be used, which could be named floating_exact_eq.

I tried looking up other material about this subject, and while there is 
plenty of material about how to do floating point code right, I didn't 
find any suggestion similar to this one.

I also wrote this suggestion at my blog, and discussed it a little bit 
on #python. I'll be glad to read other peoples' thoughts on this.

Cheers,
Imri
-- 
-------------------------
Imri Goldberg
www.algorithm.co.il/blogs
www.imri.co.il
-------------------------
Insert Signature Here
-------------------------


More information about the Python-Dev mailing list