a.index(float('nan')) fails

Chris Angelico rosuav at gmail.com
Fri Oct 26 21:29:46 EDT 2012


On Sat, Oct 27, 2012 at 5:40 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sat, 27 Oct 2012 03:45:46 +1100, Chris Angelico wrote:
>>
>> Actually, as I see it, there's only one principle to take note of: the
>> "HMS Pinafore Floating Point Rule"...
>>
>> ** Floating point expressions should never be tested for equality **
>> ** What, never? **
>> ** Well, hardly ever! **
>>
>> The problem isn't with the associativity, it's with the equality
>> comparison. Replace "x == y" with "abs(x-y)<epsilon" for some epsilon
>> and all your statements fulfill people's expectations.
>
> O RYLY?
>
> Would you care to tell us which epsilon they should use?
>
> Hint: *whatever* epsilon you pick, there will be cases where that is
> either stupidly too small, stupidly too large, or one that degenerates to
> float equality. And you may not be able to tell if you have one of those
> cases or not.
>
> Here's a concrete example for you:
>
> What *single* value of epsilon should you pick such that the following
> two expressions evaluate correctly?
>
> sum([1e20, 0.1, -1e20, 0.1]*1000) == 200
> sum([1e20, 99.9, -1e20, 0.1]*1000) != 200

Your epsilon value needs to take into account the precisions of the
values involved, and each operation needs to modify the
precision/error value. That's how I was taught to do it in
mathematical calculations. Well, I was taught "significant digits",
counting decimal digits, and a computer would normally want to count
"bits of precision", but close enough.

So here's my heresy: When you add 1e20 and 0.1, the value should be
equal to the original 1e20 unless it has at least 21 significant
digits. Otherwise, you get stupidly accurate errors, like in the old
anecdote about the age of a museum piece: It's 1001 years, 2 months,
and 3 days old, because I asked last year how old it was and it was a
thousand years old.

Flame away!

ChrisA



More information about the Python-list mailing list