Java double, float type comparison size or equal method-soanr scanning problem Floating point numbers should not be tested for equality

Due to the challenge of storing these values ​​in a binary representation, floating-point math is inaccurate. Worse, floating-point math is not associative; pushing floator doublepassing a series of simple mathematical operations, the answer will vary according to the order of these operations due to the rounding that occurs at each step.

Even simple floating-point assignments are not simple:

float f = 0.1; // 0.100000001490116119384765625 
double d = 0.1; // 0.1000000000000000055511151231257827021181583404541015625

(The results will vary according to the compiler and compiler settings);

Therefore, using equality ( ==) and inequality ( !=) operators on values ​​or values ​​is almost always a mistake. Instead, the best approach is to avoid floating-point comparisons altogether. If it is not possible, you should consider using one of Java's floating point processing, for example, floating point comparisons can be handled correctly. The third option is not to consider equality, but to consider whether the value is close enough. That is, the absolute value of the difference between the stored value and the expected value is compared with the margin of acceptable error. Please note that this does not cover up all cases (and is an example).floatdoubleNumbersBigDecimalNaNInfinity

This rule examines the use of floating-point and double-precision direct and indirect equality / not equal test.

Non-compliant code examples

float myNumber = 3.146; 
if(myNumber == 3.146f){//不合规。由于浮点不精确,这将是假的
  ... ... 
} 
if(myNumber!= 3.146f){//不合规。由于浮点不精确,这将是真的
  // ... 
} 

如果(myNumber <4 || myNumber> 4){//不合规; 间接不等式检验
  // ... 
} 

float zeroFloat = 0.0f; 
if(zeroFloat == 0){//不合规。计算可能最终得到一个接近但不等于零的值。
}

Solution

Two real numbers are equal: the difference between the two real numbers is considered to be equal within the allowed range and can be considered equal.

Range: 1e-6 (0.000001)

Main code:

 

boolean IsEqual(double a,double b)
{
    //计算机表示浮点数(float或double类型)都有一个精度限制,对于超出了精度限制的浮点数,计算机会把它们的精度之外的小数部分截断。因此,本来不相等的两个浮点数在计算机中可能就变成相等的了
//因此一般不会直接用“==”或者“!=”对两个浮点数进行比较。判断两个浮点数是否相等可以根据他们的差的绝对值是否大于0来进行判断。
//考虑到实际应用,一般如果两个浮点数之差的绝对值小于或等于某一个可接受的误差(即精度,比如0.00000001即可),就认为它们是相等的。
    return Math.abs(a-b) < 0.000001;
}

 

Published 13 original articles · Like 3 · Visits 4999

Guess you like

Origin blog.csdn.net/u010919402/article/details/88187968