float("nan") in set or as key

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jun 3 01:59:17 EDT 2011


On Fri, 03 Jun 2011 14:35:52 +1000, Chris Angelico wrote:

> On Fri, Jun 3, 2011 at 2:23 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>>> You can't get a valid result from data produced by an invalid
>>> computation. Garbage in, garbage out.
>>
>> Of course you can. Here's a trivial example:
>>
>> def f(x):
>>    return 1
>>
>>
> If your incoming x is garbage, your outgoing 1 is also garbage.

If there were non-garbage input where f(x) would return something other 
than 1, then you might argue that "well, we can't be sure what value 
f(x) should return, so we better return a NAN". But there is no such 
input.

NANs are a tool, not poison. They indicate an invalid calculation. Not 
all calculations are critical. What do you do when you reach an invalid 
calculation and you can't afford to just give up and halt the program 
with an error? You try to fix it with another calculation!

If you're in the fortunate situation that you can say "this bad input 
does not matter", then *that input does not matter*. Regardless of 
whether your input is a NAN, or you've just caught an exception, you have 
the opportunity to decide what the appropriate response is.

You might not be able to fix the situation, in which case it is 
appropriate to return a NAN to signal to the next function that you don't 
have a valid result. But sometimes one bad value is not the end of the 
world. Perhaps you try again with a smaller step size, or you skip this 
iteration of the calculation, or you throw away the current value and 
start again from a different starting point, or do whatever is needed to 
get the result you want.

In the case of my toy function, whatever is needed is... nothing at all. 
Just return 1, the same as you would for any other input, because the 
input literally does not matter for the output.


-- 
Steven



More information about the Python-list mailing list