在python中比较`float`和`float64` [英] Compare `float` and `float64` in python
问题描述
我必须比较两个数字.其中之一来自regulat python代码,其他来自numpy.调试器显示它们具有相同的值'29 .0',但是第一个的类型为float
,第二个的类型为float64
,因此a == b
和a - b == 0
为False
.我该如何处理?有什么办法
是否默认将常规python变量设置为float64
或numpy使用float
?
I have to compare two numbers. One of them comes from regulat python code and comes other from numpy. Debugger shows they have same value '29.0', but type of first is float
and type of second is float64
, so a == b
and a - b == 0
is False
. How can I deal with it? Is there any way to
force a regular python variable to be float64
or numpy use float
by default?
更新:最后,所有这些值都来自写入29.0
的同一文件,因此我认为数字值没有区别.
Update: In the end of all these values comes from the same file where 29.0
is written, so I don't think there are differences in numeric values.
推荐答案
在任何编程语言中,都不应该将浮点数与相等进行比较,因为您永远不会知道它们是完全相等的.相反,您应该测试它们的差异是否小于公差:
You should not compare floats with equality, in any programming language, because you can never know that they are exactly equal. Instead, you should test whether their difference is smaller than a tolerance:
if abs(a - b) < 1e-10
因此,此问题与float
和float64
之间的差异无关(Python自动将它们转换),但与比较浮点数是否相等的根本问题有关.
So this problem doesn't have to do with the difference between float
and float64
(Python converts them automatically), but with the fundamental problem of comparing floats for equality.
这篇关于在python中比较`float`和`float64`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!