math.isclose

Full name
math.isclose
Library
math
Syntax

math.isclose(a, b, *, rel_tol = 1e-09, abs_tol = 0.0)

Description

The math.isclose function returns the Boolean True if the two numbers indicated as arguments are close enough, or False otherwise. The concept of "proximity" is given by the rel_tol and abs_tol parameters.

Parameters
  • a, b: Numbers to compare
  • rel_tol: Relative tolerance. It is the maximum relative difference between both numbers for the function to return True. This difference is expressed as a fraction of the difference with respect to the maximum number. By default it is 1e-9.
  • abs_tol: Absolute tolerance. It is the maximum difference between both numbers in absolute value. By default it takes the value 0.
Result

The result returned by the math.isclose function is a Boolean.

Examples

The numbers 4 and 4.1 differ by 0.1. This means that if we set the absolute maximum tolerance to 0, logically they will not be considered "close enough":

math.isclose(4, 4.1, abs_tol = 0)

False

If we set this tolerance at 0.0999999, they would still not be close:

math.isclose(4, 4.1, abs_tol = 0.09999)

False

However, if the tolerance is set to 0.1 (or higher), the function would already return the value True :

math.isclose(4, 4.1, abs_tol = 0.1)

True

Continuing with the same numbers, their relative difference (with respect to the largest of them) is:

rel = (4.1 - 4) / 4.1
rel

0.02439024390243894

... that is, 2.4% (roughly).

If we set the relative tolerance at, for example, 0.24, the function would not consider both numbers close enough:

math.isclose(4, 4.1, rel_tol = 0.024)

False

However, if we set the relative tolerance to 0.25, now the function would already return the value True:

math.isclose(4, 4.1, rel_tol = 0.025)

True

Submitted by admin on Wed, 01/20/2021 - 16:26