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

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

In the following program, we take two numbers: 4.1 and 4.2, and check if these two numbers 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 Code Copy

Output

isclose(a, b) : True

2. Check if 4.1 and 4.2 are close with a tolerance of 0.05

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 Code Copy

Output

isclose(a, b) : False

Summary

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

Code copied to clipboard successfully 👍