Python cmath.isclose() Function



The Python cmath.isclose() function is used to verify whether two floating points are close to each other within the specific tolerance. If the given values are close then this function returns True else it returns False.

When two numbers are close to each other mathematically these values are represented as −

|a - b|  max(rel_tol  max(|a|, |b|), abs_tol)
  • If the absolute difference between two numbers is less than or equal to the relative tolerance, then this function returns "True"; otherwise, "False".
  • If either the values of a and b are NaN, then the result is always False.

Syntax

Following is the basic syntax of the Python cmath.isclose() function −

cmath.isclose(a, b, *, rel_tol=1e-9, abs_tol=0.0)

Parameters

  • a − This is the numeric value that represents the first number.
  • b − This is the numeric value that represents the second number.
  • rel_tol − Here relative tolerance is the float representation. Default value of relative tolerance is 1e-9.
  • abs_tol − Here absolute tolerance is the float representation. Default value of absolute tolerance is 0.0.

Return Values

This method returns Boolean value i.e., True or False.

Example 1

In the below example, we will check if the sum of 0.2 and 0.3 is equal to 0.5 using the cmath.isclose() function. If the values are equal, then True will be retrieved.

import cmath
x = cmath.isclose(0.2+0.3,  0.5)
print(x)

Output

The output obtained is as follows −

True

Example 2

Here, we are checking if the numbers "2000" and "2002" are equal with a relative tolerance of "0.002" using the cmath.isclose() function and an absolute tolerance of "0.02".

import cmath
res = cmath.isclose(2000, 2002, rel_tol=0.002, abs_tol=0.02)
print(res)

Output

Following is the output of the above code −

True

Example 3

In the following example, we are comparing large numbers, i.e., "1e10" and "1e10+1", with a relative tolerance of "0.001" using the cmath.isclose() function.

import cmath 
x = cmath.isclose(1e10, 1e10+1, rel_tol=0.001)
print(x)

Output

The result is obtained as follows −

True
python_modules.htm
Advertisements