Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Doubles in Visual Studio - a standard way to catch this?

Tags:

c#

Even experienced programmers write C# code like this sometimes:

double x = 2.5;
double y = 3;
if (x + 0.5 == 3) {
    // this will never be executed
}

Basically, it's common knowledge that two doubles (or floats) can never be precisely equal to each other, because of the way the computer handles floating point arithmetic.

The problem is, everyone sort-of knows this, but code like this is still all over the place. It's just so easy to overlook.

Questions for you:

  • How have you dealt with this in your development organization?
  • Is this such a common thing that the compiler should be checking that we all should be screaming really loud for VS2010 to include a compile-time warning if someone is comparing two doubles/floats?

UPDATE: Folks, thanks for the comments. I want to clarify that I most certainly understand that the code above is incorrect. Yes, you never want to == compare doubles and floats. Instead, you should use epsilon-based comparison. That's obvious. The real question here is "how do you pinpoint the problem", not "how do you solve the technical issue".

like image 598
Alex Weinstein Avatar asked Dec 17 '25 22:12

Alex Weinstein


1 Answers

Floating point values certainly can be equal to each other, and in the case you've given they always will be equal. You should almost never compare for equality using equals, but you do need to understand why - and why the example you've shown isn't appropriate.

I don't think it's something the compiler should necessarily warn about, but you may want to see whether it's something FxCop can pick up on. I can't see it in the warning list, but it may be there somewhere...

Personally I'm reasonably confident that competent developers would be able to spot this in code review, but that does rely on you having a code review in place to start with. It also relies on your developers knowing when to use double and when to use decimal, which is something I've found often isn't the case...

like image 141
Jon Skeet Avatar answered Dec 20 '25 12:12

Jon Skeet