Python math.isclose()方法

Pythonmath.isclose() 方法是一种有效的方法来寻找两个指定的值是否接近。为了衡量接近程度,它使用相对和绝对公差。

math.isclose() 使用以下公式来比较指定的两个值:

abs(x-y) <= max(rel_tol * max(abs(x), abs(y)), abs_tol)

语法

math.isclose(x, y) #with default tolerances
math.isclose(x, y, rel_tol, abs_tol) #without default tolerances

参数

x 一个正数或负数。
y 一个正数或负数。
rel_tol (可选)相对于xy 的大小,被认为是close 的最大差异。默认值是1e-09.
abs_tol (可选)被认为是close 的最大差异,与xy 的大小无关。默认值是0.

返回

如果xy 在指定的条件下相互接近,math.isclose() 返回True ;否则,False

代码示例

让我们来学习使用math.isclose() 方法,有/无默认的公差。

使用带有自定义公差的math.isclose() 方法

示例代码:

import math
x = 100
y = 50
value= math.isclose(x, y, rel_tol = 0.5 , abs_tol = 0.4)
print(f"Are {x} and {y} close enough to each other? {value}")
x = 100
y = 5
value= math.isclose(x, y, rel_tol = 0.5 , abs_tol = 0.4)
print(f"Are {x} and {y} close enough to each other? {value}")
x = 1
y = 1
value= math.isclose(x, y, rel_tol = 0.05 , abs_tol = 0)
print(f"Are {x} and {y} close enough to each other? {value}")
x = -100
y = -87
value= math.isclose(x, y, rel_tol = 0.05 , abs_tol = 0.9)
print(f"Are {x} and {y} close enough to each other? {value}")

输出:

Are 100 and 50 close enough to each other? True
Are 100 and 5 close enough to each other? False
Are 1 and 1 close enough to each other? True
Are -100 and -87 close enough to each other? False

请注意,输入的数值要被认为是close ,两个数字之间的差值必须至少小于其中一个公差。

使用math.isclose() 方法,使用默认的公差

示例代码:

import math
x = 49.5
y = 50
value= math.isclose(x, y)
print(f"Are {x} and {y} close enough to each other? {value}")
x = -32
y = -3
value= math.isclose(x, y)
print(f"Are {x} and {y} close enough to each other? {value}")
x = -3
y = -3
value= math.isclose(x, y)
print(f"Are {x} and {y} close enough to each other? {value}")
x = 49.501234567892
y = 49.501234567891
value= math.isclose(x, y)
print(f"Are {x} and {y} close enough to each other? {value}")
x = math.inf
y = 4
value= math.isclose(x, y)
print(f"Are {x} and {y} close enough to each other? {value}")

输出:

Are 49.5 and 50 close enough to each other? False
Are -32 and -3 close enough to each other? False
Are -3 and -3 close enough to each other? True
Are 49.501234567892 and 49.501234567891 close enough to each other? True
Are inf and 4 close enough to each other? False

注意这个方法的默认公差是1e-09 ,确保两个输入的数值在大约9 的小数位内是相同的。