Exercise 3: Why Sentinel-Value Checks Fail on NaN — Possible Solution ==================================================================== WHY "if x == some_error_sentinel" FAILS ------------------------------ This chapter verified directly that NaN is defined by IEEE 754 to compare unequal to every value, including itself: nan == nan evaluates to False. This isn't limited to comparing NaN against other NaN values - it applies to a comparison against ANY value whatsoever, including a chosen sentinel. If the incoming value happens to be NaN, the expression x == some_error_sentinel will evaluate to False regardless of what some_error_sentinel actually is, because NaN never equals anything under ==. So a NaN value would silently slip past this check and be treated as valid, ordinary data, which is exactly the bug the check was trying to prevent. WHAT ACTUALLY WORKS ------------------------------ Two options, both grounded in this chapter's own verified findings: 1. Use a dedicated is-NaN check, such as Python's math.isnan(x) (or equivalent library functions in other languages). This is the clearest, most explicit, and generally recommended approach, since it says exactly what it's testing for. 2. Exploit NaN's own verified self-inequality directly: if x != x: # x is NaN This works because NaN is the only floating-point value for which x != x is ever true - every other value, including Infinity and 0.0, is always equal to itself. This chapter verified this exact property directly (nan != nan evaluates to True). WHY A DEDICATED CHECK IS STILL PREFERABLE ------------------------------ While x != x is a genuinely correct and interesting property, code that relies on it can be confusing to a future reader who doesn't already know the NaN self-inequality rule - it looks like a typo or a bug at first glance. A named function like math.isnan(x) documents the intent directly and is the safer choice for real production code, even though both approaches are mathematically equivalent and equally correct. WHY THIS WORKS AS AN ANSWER ------------------------------ The explanation traces the specific failure mode back to this chapter's own verified nan == nan finding rather than a general claim that "NaN is weird," and offers both a conceptually illuminating fix (x != x, using the same verified property in reverse) and the practically preferable one (a dedicated isnan function), explaining why the second is the better real-world choice despite both being correct.