Python数学库 | isclose() 方法
在Python数学模块中, math.isclose()
方法用于判断两个浮点数的值是否接近。要使用此函数,您必须导入数学模块。
Syntax: isclose(a, b, rel_tol = 1e-09, abs_tol 0.0)
Parameters:
rel_tol: maximum difference for being considered “close”, relative to the magnitude of the input values
abs_tol: maximum difference for being considered “close”, regardless of the magnitude of the input values
-> rel_tol
and abs_tol
can be changed by using keyword argument, or by simply providing directly as according to their positions in the parameter list.
Return Value : Return True if a is close in value to b, and False otherwise.
注意:对于被认为接近的值,它们之间的差异必须小于至少一个公差。
代码#1:
# Importing Math module
import math
# printing whether two values are close or not
print(math.isclose(2.005, 2.005))
print(math.isclose(2.005, 2.004))
print(math.isclose(2.006, 2.005))
输出:
True
False
False
代码#2:
# Importing Math module
import math
# printing whether two values are close or not
print(math.isclose(2.005, 2.125, abs_tol = 0.25))
print(math.isclose(2.547, 2.0048, abs_tol = 0.5))
print(math.isclose(2.0214, 2.00214, abs_tol = 0.02))
输出:
True
False
True
您可以更改绝对容差,因为在上述情况下,绝对容差在所有三种情况下都不同。
参考: Python数学库