Python -- floating point arithmetic

Ethan Furman ethan at stoneleaf.us
Thu Jul 8 09:10:06 EDT 2010


Wolfram Hinderer wrote:
> On 7 Jul., 19:32, Ethan Furman <et... at stoneleaf.us> wrote:
> 
>>Nobody wrote:
>>
>>>On Wed, 07 Jul 2010 15:08:07 +0200, Thomas Jollans wrote:
>>
>>>>you should never rely on a floating-point number to have exactly a
>>>>certain value.
>>
>>>"Never" is an overstatement. There are situations where you can rely
>>>upon a floating-point number having exactly a certain value.
>>
>>It's not much of an overstatement.  How many areas are there where you
>>need the number
>>0.100000000000000005551115123125782702118158340454101562500000000000?
>>
>>If I'm looking for 0.1, I will *never* (except by accident ;) say
>>
>>if var == 0.1:
>>
>>it'll either be <= or >=.
> 
> 
> The following is an implementation of a well-known algorithm.
> Why would you want to replace the floating point comparisons? With
> what?

<snip code>

Interesting.  I knew when I posted my above comment that I was ignoring 
such situations.  I cannot comment on the code itself as I am unaware of 
the algorithm, and haven't studied numbers extensively (although I do 
find them very interesting).

So while you've made your point, I believe mine still stands -- 
comparing floats using == to absolute numbers is almost always a mistake.

~Ethan~



More information about the Python-list mailing list