Identify a floating-point not-a-number result.
What It Does and Why It Matters
isnan(value) checks for NaN. NaN does not compare equal to itself, so equality checks are not the standard way to detect it.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
import math
print(math.isnan(float("nan")))
How the Code Works
- The imports make these standard-library tools available: math.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
True
For the demonstrated inputs, Python displays 'True'. This result follows from the operation described above; change one input at a time to understand which rule matters.
Second Example: Compare Two Cases
Use a different input or a related operation to observe an important difference. The two examples help separate the general rule from one particular result.
import math
print(math.nan == math.nan)
print(math.isnan(math.nan))
Expected output:
False
True
Where You Would Use This
Use this in calculations, data summaries, simulations or validation when the numerical assumptions match the task. Check input domains, units and precision before interpreting a result. A single example output does not prove a statistical conclusion.
Practice Exercise
Filter out NaN measurements before calculating an average.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Using value == float("nan") to detect NaN.
- Overlooking the documented condition: naN does not compare equal to itself, so equality checks are not the standard way to detect it.
Key Takeaways
- Identify a floating-point not-a-number result.
- isnan(value) checks for NaN.
- Filter out NaN measurements before calculating an average.