Skip to content

Commit 0b94d20

Browse files
authored
docs: mention pytest.approx in Assertions guide
1 parent 09a9c6a commit 0b94d20

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

doc/en/how-to/assert.rst

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,32 @@ See :ref:`assert-details` for more information on assertion introspection.
6666

6767
.. _`assertraises`:
6868

69+
Assertions about approximate equality
70+
-------------------------------------
71+
72+
When comparing floating point values (or arrays of floats), small rounding
73+
errors are common. Instead of using ``assert abs(a - b) < tol`` or
74+
``numpy.isclose``, you can use :func:`pytest.approx`:
75+
76+
.. code-block:: python
77+
78+
import pytest
79+
import numpy as np
80+
81+
def test_floats():
82+
assert (0.1 + 0.2) == pytest.approx(0.3)
83+
84+
def test_arrays():
85+
a = np.array([1.0, 2.0, 3.0])
86+
b = np.array([0.9999, 2.0001, 3.0])
87+
assert a == pytest.approx(b)
88+
89+
``pytest.approx`` works with scalars, lists, dictionaries, and NumPy arrays.
90+
It also supports comparisons involving NaNs.
91+
92+
See :ref:`approx` for details.
93+
94+
6995
Assertions about expected exceptions
7096
------------------------------------------
7197

0 commit comments

Comments
 (0)