使用==运算符比较float / double值 [英] comparing float/double values using == operator
问题描述
无法使用equals(== )运算符
解释 通过使用等式(==)或不等式(!=)运算符并不总是准确,因为舍入错误。 建议 比较两个浮点值,看它们是否接近于值。 IBM有一个建议,用于比较两个浮点数,使用除法而不是减法 - 这使得选择适用于所有输入范围的epsilon变得更加容易。 至于epsilon的值,我会使用 The code review tool I use complains with the below when I start comparing two float values using equality operator. What is the correct way and how to do it? Is there a helper function (commons-*) out there which I can reuse? Description Cannot compare floating-point values using the equals (==) operator Explanation Comparing floating-point values by using either the equality (==) or inequality (!=) operators is not always accurate because of rounding errors. Recommendation Compare the two float values to see if they are close in value.
IBM has a recommendation for comparing two floats, using division rather than subtraction - this makes it easier to select an epsilon that works for all ranges of input. As for the value of epsilon, I would use 这篇关于使用==运算符比较float / double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b
float a;
float b;
if(a == b)
{
..
}
if(abs(a / b-1)ε
5.96e-08
,如这个维基百科表格,或者是这个值的两倍。float a;
float b;
if(a==b)
{
..
}
if (abs(a/b - 1) < epsilon)
5.96e-08
as given in this Wikipedia table, or perhaps 2x that value.