Python math.isclose() Method

Python math 模块Python math Module

Python math.isclose()The method is used to check whether two values are close to each other. It returns True if the values are close, otherwise it returns False.

math.isclose()Determines whether two values are considered close according to the given absolute and relative tolerances.

Python Version: 3.5

The calculation formula is:

abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

Syntax

The syntax of the math.isclose() method is as follows:

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

Parameter description:

  • a-- Required, a number. If x is not a number, returns TypeError. If the value is 0 or negative, returns ValueError.
  • b-- Required, a number. If x is not a number, returns TypeError. If the value is 0 or negative, returns ValueError.
  • rel_tol-- The relative tolerance. It is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a 5% tolerance, pass rel_tol=0.05. The default tolerance is 1e-09, ensuring the two values are the same within about 9 decimal digits. rel_tol must be greater than zero.
  • abs_tol-- The minimum absolute tolerance, useful for comparisons close to zero. abs_tol must be at least zero.

Return Value

Returns a boolean value, checking whether two values are close to each other. If the values are close, it returns True; otherwise, it returns False.

Example

The following example checks whether two values are close to each other:

Example

# Import the math package
import math

# Output whether the two values are close
print(math.isclose(8.005, 8.450, abs_tol = 0.4))
print(math.isclose(8.005, 8.450, abs_tol = 0.5))

Output result:

False
True

The following example checks whether two floating-point numbers are close:

Example

# Import the math package
import math

# Can be used for floating-point number comparison

# This will output false; 0.1+0.2 does not equal 0.3
print(0.1+0.2 == 0.3)
print(0.1+0.2 )

# This will output true
print(math.isclose(0.1+0.2, 0.3))

Output result:

False
0.30000000000000004
True

Python math 模块Python math Module

Other Extensions