當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python math isclose()用法及代碼示例

在Python數學模塊中,math.isclose()方法用於確定兩個浮點數的值是否接近。要使用此函數,您必須導入數學模塊。

用法: isclose(a, b, rel_tol = 1e-09, abs_tol 0.0)

參數:
rel_tol:被視為“close”的最大差,相對於輸入值的大小
abs_tol:“close”的最大差異,與輸入值的大小無關


->rel_tolabs_tol 可以通過使用關鍵字參數或直接根據其在參數列表中的位置直接提供來更改。

返回值:如果a的值與b接近,則返回True,否則返回False。

注意:為了使值接近,它們之間的差異必須小於公差中的至少一個。

代碼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 math library



相關用法


注:本文由純淨天空篩選整理自sanjeev2552大神的英文原創作品 Python math library | isclose() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。