In the mathematical operation, it is often involved in judging whether the two numbers are equal.
For integers, one statement like A == B can solve all problems
But for floating point numbers are different
First, the binary expression in the computer is determined that most floating point numbers are unacceptable.
Most of the current computers are digital computers, not simulating, digital discrete data representation methods naturally unable to accurately express most of the amount of data.
Second, the accuracy of the computer floating point number is only 7 in the single-precision float type. When the floating point operation is performed, this accuracy tends to cause an error between the results of the operation and the actual desired results.
Because the first two reasons, we are difficult to use a == b to determine if the two floating point numbers are the same.
Very nature, we can think of a method of discrimination of FABS (A-B) But is this judgment method is safe? It is not stable. First, EPSILON is an absolute error in the error analysis. Using a fixed value, it is not possible for the entire number of FLOAT types. For example, EPSILON is 0.0001, and the value of the A and B is also 0.0001, then it is obviously not suitable. In addition, it is not suitable for the data of the A and B size of 10000, because 10,000 and 10001 can be considered equal. Suitable for it is just a or b in 1 or 0 Since we are absolutely mistaken, then we will think of relative error. Bool ISEqual (Float A, Float B, Float Relerror) { RETURN (Fabs (((A-B) / a) } This is not perfect, because it is compared to the first parameter, then call ISEQUAL (A, B, Reservor) and ISEQUAL (B, A, Reservor) may get different results At the same time, if the first parameter is 0, it is possible to except 0 overflow. This can be transformed Pick the divisor to the absolute value in A and B. Bool ISequal (Float A, Float B, Reservor) { IF (Fabs (a) RETURN (Fabs (((A-B) / B)> Relerror)? True: False; } Is it very perfect for use of relative error? Nor, in some special cases, relative errors cannot represent all For example, when judging whether there is a common line of three points in the space, use the method of judging the distance to the other two points to form the distance of the line segment formed. It is not enough to use relative errors. It should be a variety of line segments. It may also be very long, the distance from the line segment, and when the length of the line segment is compared, the relative error and absolute error in combination are required. The relatively complete comparison algorithm should be as follows: Bool ISEqual (Float A, Float B, Float Abserror, Float Relerror) { IF (a == b) return true; IF (FABS (A-B) IF (Fabs (A> B) RETURN (Fabs ((A-B) / A> Relerror)? True: false; RETURN (FABS ((A-B) / B> Relerror)? True: false; } This is relatively complete This is just the most primary comparative method between floating point numbers.