Phương thức math.isclose () trong Python
Thí dụ
Kiểm tra xem hai giá trị có gần nhau hay không:
#Import math Library
import math
#compare the closeness of two values
print(math.isclose(1.233, 1.4566))
print(math.isclose(1.233, 1.233))
print(math.isclose(1.233, 1.24))
print(math.isclose(1.233, 1.233000001))
Định nghĩa và Cách sử dụng
Phương math.isclose()
thức kiểm tra xem hai giá trị có gần nhau hay không. Trả về True nếu các giá trị gần nhau, ngược lại là False.
Phương pháp này sử dụng dung sai tương đối hoặc tuyệt đối, để xem các giá trị có gần nhau hay không.
Mẹo: Nó sử dụng công thức sau để so sánh các giá trị: abs (ab) <= max (rel_tol * max (abs (a), abs (b)), abs_tol)
Cú pháp
math.isclose(a, b, rel_tol, abs_tol)
Giá trị tham số
Parameter | Description |
---|---|
a | Required. The first value to check for closeness |
b | Required. The second value to check for closeness |
rel_tol = value | Optional. The relative tolerance. It is the maximum allowed difference between value a and b. Default value is 1e-09 |
abs_tol = value | Optional. The minimum absolute tolerance. It is used to compare values near 0. The value must be at least 0 |
Chi tiết kỹ thuật
Giá trị trả lại: | Một bool giá trị. True nếu các giá trị gần nhau, nếu khôngFalse |
---|---|
Phiên bản Python: | 3.5 |
Các ví dụ khác
Thí dụ
Sử dụng dung sai tuyệt đối:
#Import math Library
import math
#compare the closeness of two
values
print(math.isclose(8.005, 8.450, abs_tol = 0.4))
print(math.isclose(8.005, 8.450, abs_tol = 0.5))