10

I just read a statement about the floating point value comparison

Floating point values shall not be compared using either the == or != operators. Most floating point values have no exact binary representation and have a limited precision.

If so what is the best method for comparing two floating point values?

2
  • Can you explain why you need to compare them? Or are you just curious about that documentation? Commented May 28, 2012 at 17:18
  • possible duplicate of How should I do floating point comparison? Commented May 11, 2015 at 8:46

3 Answers 3

13

The following extension methods may be useful to implement Kevin's suggestion:

public static bool IsEqualTo(this double a, double b, double margin) { return Math.Abs(a - b) < margin; } public static bool IsEqualTo(this double a, double b) { return Math.Abs(a - b) < double.Epsilon; } 

So now you can just do:

if(x1.IsEqualTo(x2)) ... if(x1.IsEqualTo(x2, 0.01)) ... 

Just change the IsEqualTo to a more appropriate name, or change the default margin to anything better than double.Epsilon, if needed.

Sign up to request clarification or add additional context in comments.

Comments

5

Generally floating point numbers should be compared using a construct like

if( abs((x1 - x2) < 0.001) ) 

The reason for the warning you quoted is you may have two methods of calculating something, and they may be equal if you had no rounding error, but the rounding error makes them slightly different.

4 Comments

use abs(x1 - x2) < 0.001 * x1 instead
@Alexandre: Why? Would be helpful if you could give us some explanation.
@user411768: this is because of the "generally". Generally, you compare relative precision, not absolute. What if x1 and x2 are on the order of 10^-6, but x1 is five times as large as x2 ? You surely don't want the above construct to tell you that x1 == x2. There are cases where absolute precision is right though. The subject is difficult.
@AlexandreC. on the same subject, do you want 1001.0 == 1000.0 be true?
1

"Best method" depends on the circumstances of why you want to compare the numbers. In general, if you think you want to check if 2 floating points numbers are equal, you are doing something wrong.

Floating point numbers are supposed to be used to represent real values, in both senses of the word. Is this object the same length as this other object? Well, they may look the same length, but if you get a good enough measuring device, you can always find a difference. Similarly, two floating point numbers are never equal, unless they are measuring the same thing, and have been processed in exactly the same way. Other than that, it's just a rounding error somewhere in the system.

You might want to check that they are close, (closer than a certain threshold) as the other answers have suggested, but not equal.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.