Floating number equals | Hello World
The floating number (IEEE 754 standard) can hold a number with a decimal, however, due to the imprecise nature of the floating point numbers, we should not use == or != to compare floating point numbers directly.
So we defind an epsilon such that we define
a == b if Math.abs(a – b) <= 0.0001. However, choosing a fixed epsilon might not be a good idea because depending on your applications. If you have very small numbers, epsilon could be too large that different numbers are taken to be equal while if your application uses very large numbers, the epsilon could be smaller than the smallest rounding error, so that it will always return false.
So we are supposed to use a relative error, using somthing like
Math.abs((a – b) / b) < 0.0001, but this still might fail when b equals zero.
This solution is by no means the universal solution for all the floating point numbers and you should design the floating point numbers equality function based your own application and test cases.
The floating number (IEEE 754 standard) can hold a number with a decimal, however, due to the imprecise nature of the floating point numbers, we should not use == or != to compare floating point numbers directly.
So we defind an epsilon such that we define
a == b if Math.abs(a – b) <= 0.0001. However, choosing a fixed epsilon might not be a good idea because depending on your applications. If you have very small numbers, epsilon could be too large that different numbers are taken to be equal while if your application uses very large numbers, the epsilon could be smaller than the smallest rounding error, so that it will always return false.
So we are supposed to use a relative error, using somthing like
Math.abs((a – b) / b) < 0.0001, but this still might fail when b equals zero.
This solution is by no means the universal solution for all the floating point numbers and you should design the floating point numbers equality function based your own application and test cases.
public static boolean nearlyEqual(float a, float b, float epsilon) {
final float absA = Math.abs(a);
final float absB = Math.abs(b);
final float diff = Math.abs(a - b);
if (a == b) { // shortcut, handles infinities
return true;
} else if (a == 0 || b == 0 || diff < Float.MIN_NORMAL) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Float.MIN_NORMAL);
} else { // use relative error
return diff / (absA + absB) < epsilon;
}
}
Read full article from Floating number equals | Hello World