python 比较大小 容差 0.001
时间: 2023-12-05 16:41:16 浏览: 95
可以使用Python中的abs()函数来比较两个数的大小,并设置一个容差值。具体实现如下所示:
```python
def compare_with_tolerance(a, b, tolerance):
if abs(a - b) < tolerance:
print("a and b are equal within the tolerance of", tolerance)
elif a > b:
print("a is greater than b by more than the tolerance of", tolerance)
else:
print("b is greater than a by more than the tolerance of", tolerance)
# 示例
compare_with_tolerance(1.0001, 1.0002, 0.001) # 输出:a and b are equal within the tolerance of 0.001
compare_with_tolerance(1.0001, 1.0003, 0.001) # 输出:a is greater than b by more than the tolerance of 0.001
compare_with_tolerance(1.0003, 1.0001, 0.001) # 输出:b is greater than a by more than the tolerance of 0.001
```
阅读全文