---
jupytext:
  formats: content_md///md:myst,content///ipynb
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.13.8
kernelspec:
  display_name: Python 3 (ipykernel)
  language: python
  name: python3
---

(managing-data:numpy:special-floats)=
# Special Floats

NumPy does not raise an exception if we use mathematical operations which lead to undefined results. Instead, NumPy prints a warning and returns one of several special floating point numbers.

```{code-cell} ipython3
import numpy as np
```

## Infinity

Results of some undefined operations can be interpreted as plus or minus infinity. NumPy represents infinity by the special float `np.inf`:

```{code-cell} ipython3
a = np.array([1, -1])
b = a / 0

print(b)
print(type(b[0]))
```

If there is some good reason we may also use `np.inf` in assignments:

```{code-cell} ipython3
a = np.inf

print(a)
```

Also well defined operations may lead to infinity if the range of floats is exhausted:

```{code-cell} ipython3
print(np.array([1.23]) ** 10000)
```

Calculations with `np.inf` behave as expected:

```{code-cell} ipython3
print(np.inf + 1)
print(5 * np.inf)
print(0 * np.inf)
print(np.inf - np.inf)
```

## Not a Number

Results of undefined operations which cannot be interpreted as infinity are represented by the special float `np.nan` (**n**ot **a** **n**umber).

```{code-cell} ipython3
a = np.array([-1, 1])
b = np.log(a)

print(b)
```

Calculations with `np.nan` always lead to `np.nan`:

```{code-cell} ipython3
print(np.nan + 1)
print(5 * np.nan)
print(0 * np.nan)
```

## Comparison of and to Special Floats

Don't use usual comparison operators for testing for special floats. They show strange (but well-defined) behavior:

```{code-cell} ipython3
print(np.nan == np.nan)
print(np.inf == np.inf)
```

Instead, call [`np.isnan`](https://numpy.org/doc/stable/reference/generated/numpy.isnan.html) or [`np.isposinf`](https://numpy.org/doc/stable/reference/generated/numpy.isposinf.html) (for $+\infty$) or [`np.isneginf`](https://numpy.org/doc/stable/reference/generated/numpy.isneginf.html) (for $-\infty$) or [`np.isinf`](https://numpy.org/doc/stable/reference/generated/numpy.isinf.html) (for both).

Comparisons between finite numbers and `np.inf` are okay:

```{code-cell} ipython3
print(5 < np.inf)
```

## NumPy Functions Handling `np.nan`

Some NumPy function come in two variants, which differ in handling `np.nan`. Look at [amin](https://numpy.org/doc/stable/reference/generated/numpy.amin.html) and [nanmin](https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html), for instance.
