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 |
(可选)相对于x 和y 的大小,被认为是close 的最大差异。默认值是1e-09.
|
abs_tol |
(可选)被认为是close 的最大差异,与x 和y 的大小无关。默认值是0.
|
返回
如果x
和y
在指定的条件下相互接近,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
的小数位内是相同的。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。