0

I'm having a problem in both Java and MATLAB where two numbers which should be the same apparently aren't.

Java:

float f1 = 0.3f-0.2f;
float f2 = 0.4f-0.3f;
System.out.println(f1==f2); // Prints false

System.out.println(f1); // Prints 0.10000001
System.out.println(f2); // Prints 0.099999994

Obviously f1 should be equal to f2. What is the most efficient (computationally) method to replace equals below that would return true?

public boolean equals(float f1, float f2){
    return f1 == f2;
}

I will need to operate on hundreds of thousands of floats so optimization is important here.

Eduardo
  • 6,900
  • 17
  • 77
  • 121
  • "Obviously `f1` should be equal to `f2`" - yeah no – Kevin L Jul 30 '14 at 16:30
  • 2
    `f1` and `f2` _don't_ have to be equal, or else they would be; the chance that you've found a bug in such a basic part of the JVM is pretty low. :) This is due to floating-point rounding errors. See for instance http://floating-point-gui.de – yshavit Jul 30 '14 at 16:30
  • 1
    What is the purpose of this comparison? What is the range of magnitude of numbers to which it is applied? Those issues affect how elaborate the comparison needs to be. – Patricia Shanahan Jul 30 '14 at 16:31
  • 1
    This topic has been covered [many](http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab) [times](http://stackoverflow.com/questions/linked/686439?lq=1) by now (both in the MATLAB tag and elsewhere)... Here is a recent two parts blog post by Cleve Moler (founder of MATLAB) on the subject of floating points: http://blogs.mathworks.com/cleve/2014/07/07/floating-point-numbers/, http://blogs.mathworks.com/cleve/2014/07/21/floating-point-denormals-insignificant-but-controversial-2/ – Amro Jul 30 '14 at 17:43

1 Answers1

4

The best way to compare floating point numbers is to pick some small epsilon, and then compare the difference of between the two floats is less than that epsilon. I.e.

if ( Math.abs(f1 - f2) < .00001){
    return true;
}
jhobbie
  • 1,016
  • 9
  • 18