Ref Math Nan
## Python math.nan Constant
The `math.nan` constant in Python returns a floating-point **NaN** (Not a Number) value. This value represents an undefined or unrepresentable numerical value (such as the result of `0.0 / 0.0`).
`math.nan` is equivalent to the output of `float('nan')`.
---
### Syntax
To use the `math.nan` constant, you must first import the `math` module:
```python
import math
math.nan
```
### Return Value
* Returns a **float** value representing `nan`.
---
### Code Example
The following example demonstrates how to access `math.nan` and inspect its data type:
```python
# Import the math module
import math
# Output the value of math.nan
print(math.nan)
# Output the data type of math.nan
print(type(math.nan))
```
**Output:**
```text
nan
```
---
### Key Considerations & Best Practices
When working with `math.nan` in Python, keep the following behaviors in mind:
#### 1. Checking for NaN Values
You **cannot** use the standard comparison operators (`==` or `is`) to check if a value is `nan`. By definition, NaN is not equal to anything, including itself.
```python
import math
x = math.nan
# This will evaluate to False!
print(x == math.nan) # Output: False
print(x == float('nan')) # Output: False
```
To correctly check if a value is NaN, use the **`math.isnan()`** function:
```python
import math
x = math.nan
# Correct way to check for NaN
print(math.isnan(x)) # Output: True
```
#### 2. Type Compatibility
Because `math.nan` is of type `float`, it can be used in mathematical operations and stored in data structures (like NumPy arrays or Pandas DataFrames) that require uniform numeric types. However, any arithmetic operation involving `nan` will result in `nan`:
```python
import math
print(math.nan + 5) # Output: nan
print(math.nan * 0) # Output: nan
```
YouTip