Python math.isclose() 方法
示例
检查两个值是否彼此接近
#导入 math 库
import math
# 比较两个值的接近程度
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))
自己动手试一试 »
定义和用法
math.isclose()
方法检查两个值是否彼此接近。如果值接近则返回 True,否则返回 False。
此方法使用相对或绝对容差来判断值是否接近。
提示:它使用以下公式来比较值:abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
语法
math.isclose(a, b, rel_tol, abs_tol)
参数值
参数 | 描述 |
---|---|
a | 必需。第一个要检查接近度的值 |
b | 必需。第二个要检查接近度的值 |
rel_tol = 值 | 可选。相对容差。它是值 a 和 b 之间允许的最大差异。默认值为 1e-09 |
abs_tol = 值 | 可选。最小绝对容差。用于比较接近 0 的值。该值必须至少为 0 |
技术详情
返回值 | 一个 bool 值。True 表示值接近,否则为 False |
---|---|
Python 版本 | 3.5 |
更多示例
示例
使用绝对容差
#导入 math 库
import math
# 比较两个值的接近程度
print(math.isclose(8.005, 8.450, abs_tol = 0.4))
print(math.isclose(8.005, 8.450, abs_tol = 0.5))
自己动手试一试 »