Skip to content

Commit b1e100d

Browse files
authored
Docs: mention pytest.approx in assert and getting-started documentation (#13788)
Fixes #13662
1 parent 83da343 commit b1e100d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

doc/en/getting-started.rst

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,26 @@ This is outlined below:
199199
200200
Note that attributes added at class level are *class attributes*, so they will be shared between tests.
201201

202+
Compare floating-point values with pytest.approx
203+
--------------------------------------------------------------
204+
205+
``pytest`` also provides a number of utilities to make writing tests easier.
206+
For example, you can use :func:`pytest.approx` to compare floating-point
207+
values that may have small rounding errors:
208+
209+
.. code-block:: python
210+
211+
# content of test_approx.py
212+
import pytest
213+
214+
215+
def test_sum():
216+
assert (0.1 + 0.2) == pytest.approx(0.3)
217+
218+
This avoids the need for manual tolerance checks or using
219+
``math.isclose`` and works with scalars, lists, and NumPy arrays.
220+
221+
202222
Request a unique temporary directory for functional tests
203223
--------------------------------------------------------------
204224

doc/en/how-to/assert.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,33 @@ 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+
82+
def test_floats():
83+
assert (0.1 + 0.2) == pytest.approx(0.3)
84+
85+
86+
def test_arrays():
87+
a = np.array([1.0, 2.0, 3.0])
88+
b = np.array([0.9999, 2.0001, 3.0])
89+
assert a == pytest.approx(b)
90+
91+
``pytest.approx`` works with scalars, lists, dictionaries, and NumPy arrays.
92+
It also supports comparisons involving NaNs.
93+
94+
See :func:`pytest.approx` for details.
95+
6996
Assertions about expected exceptions
7097
------------------------------------------
7198

0 commit comments

Comments
 (0)