---
jupyter:
  jupytext:
    text_representation:
      extension: .Rmd
      format_name: rmarkdown
      format_version: '1.2'
      jupytext_version: 1.11.5
  kernelspec:
    display_name: Python 3 (ipykernel)
    language: python
    name: python3
---

# Testing for near equality with “allclose”

When the computer calculates a floating point value, there will often be some
degree of error in the calculation, because the computer floating point format
cannot represent every floating point number exactly. See:

* [floating point](https://matthew-brett.github.io/teaching/floating_point.html);

* [floating point error](https://matthew-brett.github.io/teaching/floating_error.html).

When we check the results of a floating point calculation, we often want to
avoid checking if the returned value is exactly equal to a desired value.
Rather, we want to check whether the returned value is close enough, given the
usual floating point error.  A common idiom in NumPy is to use the
[`np.allclose`](https://numpy.org/doc/stable/reference/generated/numpy.allclose.html)
function, which checks whether two values or two arrays are equal, within a
small amount of error:

```{python}
import numpy as np
```

```{python}
np.pi == 3.1415926
```
```{python}
# pi to 7 decimal places not exactly equal to pi
np.allclose(np.pi, 3.1415926)
```
```{python}
# pi to 7 dp is "close" to pi
np.allclose([np.pi, 2 * np.pi], [3.1415926, 6.2831852])
```

See the docstring for
[`np.allclose`](https://numpy.org/doc/stable/reference/generated/numpy.allclose.html)
for details of what “close” means.
