Categories
Python Answers

How to assert almost equal with Python pytest?

Spread the love

In Python pytest, we can assert that two floating-point numbers are almost equal using the pytest.approx() function.

This function allows we to compare floating-point numbers with a certain tolerance, which accounts for small differences due to floating-point arithmetic.

To do this were write

import pytest

def test_almost_equal():
    # Define two floating-point numbers
    x = 0.1 + 0.2
    y = 0.3

    # Assert that x is almost equal to y with a tolerance of 1e-6
    assert x == pytest.approx(y, abs=1e-6)

In this example, pytest.approx() is used to assert that x is almost equal to y with a tolerance of 1e-6 (i.e., 0.000001).

This tolerance accounts for small differences that may arise due to floating-point arithmetic.

We can adjust the abs parameter of pytest.approx() to set the desired tolerance level based on our requirements.

Alternatively, we can use the rel parameter to specify a relative tolerance instead of an absolute tolerance.

If the two values are not almost equal within the specified tolerance, the test will fail, and pytest will provide details about the assertion failure.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *