Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python
math

How to use the math.isclose() function in Python?

Vinisha Maheshwari

The math module in Python contains a number of mathematical operations, which can be performed very easily and make our lives a lot simpler. Amongst some of the most important functions in this module, is the isclose() function.

The math.isclose() function is used to check whether two given values are close to each other. The closeness of the two values is determined according to the given absolute and relative tolerances. The function returns

  • True, if the values are close.
  • False, if they are not close.

Syntax

math.isclose(a, b, rel_tol, abs_tol)

Parameters

  • a: It is a required parameter and signifies the first value to check for closeness.
  • b: It is a required parameter and signifies the second value to check for closeness.
  • rel_tol = value: It is an optional parameter and determines the relative tolerance between a and b. It has a default value of 1e-09.
  • abs_tol = value: It is an optional parameter and determines the minimum absolute tolerance. The value must be at least 0.
import math
print(math.isclose(8.005, 8.450, abs_tol = 0.4))
print(math.isclose(8.005, 8.450, abs_tol = 0.5))
Using math.isclose() function in Python

Explanation

  • In line 1, we imported the math module in Python.

  • In lines 2 and 3, we use the math.isclose() function to compare the two values.

  • The first output is false. This is because the two given numbers have an absolute difference of 0.445, while the threshold mentioned is 0.4.

  • The second output is true. This is because the two given numbers have an absolute difference of 0.445, while the threshold mentioned is 0.5.

RELATED TAGS

communitycreator
python
math
RELATED COURSES

View all Courses

Keep Exploring