.isclose()

betaAce90716's avatar
Published Jul 25, 2024
Contribute to Docs

The .isclose() function returns True when two floating-point numbers are close to each other within a specified tolerance. This is useful when comparing a value to an expected value, without requiring exact equality. For example, the comparison 0.1 + 0.2 == 0.3 returns False, but using .isclose() would return True.

Syntax

math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0)
  • a: The first float value to be compared.
  • b: The second float value to be compared.
  • rel_tol: Relative tolerance is the maximum allowed relative difference between a and b. The default value is 1e-09, which means the values are considered close if their relative difference is within 9 decimal places. The tolerance value must be greater than zero.
  • abs_tol: Absolute tolerance is the minimum absolute difference allowed between a and b. The default value is 0.0, which means no absolute tolerance is applied. This parameter can be set to any non-negative number. Absolute tolerance is particularly useful for comparisons involving values near zero.

Note: The required parameters for .isclose() are a and b; all other parameters are optional.

Example

Here is an example of .isclose():

import math
x = 0.1
y = 0.2
print(math.isclose(x + y, 0.3))
print(math.isclose(x + y, 0.3, rel_tol=0.01))
print(math.isclose(x + y, 0.3, rel_tol=1e-20))
print(math.isclose(x + y, 0.3, abs_tol=0.01))
print(math.isclose(x + y, 0.4, abs_tol=0.01))

The above code gives the following output:

True
True
False
True
False

Codebyte Example

Run the following code to understand how the .isclose() function works:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy