[Python-Dev] Why is nan != nan?
Casey Duncan
casey at pandora.com
Fri Mar 26 22:39:44 CET 2010
On Mar 26, 2010, at 3:16 PM, Xavier Morel wrote:
> On 26 Mar 2010, at 18:40 , Casey Duncan wrote:
>>
>>
>> On Mar 25, 2010, at 7:19 PM, P.J. Eby wrote:
>>
>>> At 11:57 AM 3/26/2010 +1100, Steven D'Aprano wrote:
>>>> But they're not -- they're *signals* for "your calculation has gone screwy and the result you get is garbage", so to speak. You shouldn't even think of a specific NAN as a piece of specific garbage, but merely a label on the *kind* of garbage you've got (the payload): INF-INF is, in some sense, a different kind of error to log(-1). In the same way you might say "INF-INF could be any number at all, therefore we return NAN", you might say "since INF-INF could be anything, there's no reason to think that INF-INF == INF-INF."
>>>
>>> So, are you suggesting that maybe the Pythonic thing to do in that case would be to cause any operation on a NAN (including perhaps comparison) to fail, rather than allowing garbage to silently propagate?
>>>
>>> In other words, if NAN is only a signal that you have garbage, is there really any reason to keep it as an *object*, instead of simply raising an exception? Then, you could at least identify what calculation created the garbage, instead of it percolating up through other calculations.
>>>
>>> In low-level languages like C or Fortran, it obviously makes sense to represent NAN as a value, because there's no other way to represent it. But in a language with exceptions, is there a use case for it existing as a value?
>>
>> If a NaN object is allowed to exist, that is a float operation that does not return a real number does not itself raise an exception immediately, then it will always be possible to get (seemingly) nonsensical behavior when it is used in containers that do not themselves "operate" on their elements.
> How about raising an exception instead of creating nans in the first place, except maybe within specific contexts (so that the IEEE-754 minded can get their nans working as they currently do)?
>
> That way, there cannot be any nan-induced seemingly nonsensical behavior except within known scopes.
Having NaN creation raise an exception would undoubtedly break plenty of existing code that either expects and deals with NaNs itself or works accidentally because the NaNs do not cause harm.
I don't sympathize much with the latter case since they are just hidden bugs probably, but the former makes it hard to justify raising exceptions for NaNs as the default behavior.
But since I assume we're talking Python 3 here, maybe arguments containing the phase "existing code" can be dutifully ignored, I dunno.
-Casey
More information about the Python-Dev
mailing list