What is the best way to compare floats for almost-equality in Python?(在 Python 中比较浮点数是否相等的最佳方法是什么?)
问题描述
众所周知,由于舍入和精度问题,比较浮点数是否相等有点繁琐.
It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.
例如:https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
在 Python 中处理此问题的推荐方法是什么?
What is the recommended way to deal with this in Python?
在某个地方肯定有一个标准库函数吗?
Surely there is a standard library function for this somewhere?
推荐答案
Python 3.5 添加了 math.isclose 和 cmath.isclose 函数,如 PEP 485.
Python 3.5 adds the math.isclose and cmath.isclose functions as described in PEP 485.
如果您使用的是早期版本的 Python,则在 文档.
If you're using an earlier version of Python, the equivalent function is given in the documentation.
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
rel_tol 是一个相对容差,它乘以两个参数中较大的一个;随着值变大,它们之间的允许差异也会变大,同时仍然认为它们相等.
rel_tol is a relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference between them while still considering them equal.
abs_tol 是在所有情况下按原样应用的绝对公差.如果差值小于这些公差中的任何一个,则认为这些值相等.
abs_tol is an absolute tolerance that is applied as-is in all cases. If the difference is less than either of those tolerances, the values are considered equal.
这篇关于在 Python 中比较浮点数是否相等的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中比较浮点数是否相等的最佳方法是什么
基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
