Python math.isclose() – Check if Two Numbers are Close

Python math.isclose()

math.isclose(a, b) function returns True if a and b are close to each other within given tolerance.

Syntax

The syntax to call isclose() function is

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

where

ParameterRequiredDescription
aYesA numeric value.
bYesA numeric value.
*NoMore numeric values.
rel_tolNoMaximum allowed difference between a and b.
abs_tolNoMinimum absolute tolerance.

Examples

Check if two numbers 4.1 and 4.2 are close with a tolerance of 0.2.

Python Program

import math

a = 4.1
b = 4.2
result = math.isclose(a, b, abs_tol=0.2)
print('isclose(a, b) :', result)
Run

Output

isclose(a, b) : True

Now, let us check if these two numbers are close with a tolerance of 0.05.

Python Program

import math

a = 4.1
b = 4.2
result = math.isclose(a, b, abs_tol=0.05)
print('isclose(a, b) :', result)
Run

Output

isclose(a, b) : False

Summary

In this Python Examples tutorial, we learned the syntax of, and examples for math.isclose() function.