-
Notifications
You must be signed in to change notification settings - Fork 13
/
allclose.Rmd
51 lines (43 loc) · 1.56 KB
/
allclose.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
---
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.