Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to compare double.MaxValue for equality?

Same question can be asked of float... or of MinValue.

I am thinking of using it as a special value. Will i see bugs due to precision? I don't expect to do arithmetic with these numbers, just set them and that's it.

Clarification: I am using this for a sentinel value.

Is it something that's described in a C# spec?

like image 392
GregC Avatar asked Apr 21 '11 22:04

GregC


2 Answers

It depends on how you use it.

If you're using double.MaxValue as a token or sentinel value that has special semantics, then yes, it's just a bit pattern that you're comparing against. For example, you could use double.MaxValue to indicate an "uninitialized" or "unknown" value. There are other ways to do this (e.g. with the nullable double?), but using double.MaxValue is also reasonable assuming the value doesn't naturally occur in your domain.

If you have some arbitrary double value, though, and you want to see if it's "equal" to double.MaxValue, then you'll want to see if the numbers are within some small range (epsilon) of each other since some precision could've been lost when computing your other double value. The issue to be aware of here is with values that go beyond double.MaxValue, creating an overflow situation.

like image 100
Chris Schmich Avatar answered Nov 15 '22 21:11

Chris Schmich


If you compare double.MaxValue to double.MaxValue, yes they will be the same. The binary representation is identical, there won't be a problem. If, on the other hand, you try something like:

double myDouble = (double.MaxValue - 3.1415) / 2;
if((myDouble * 2) + 3.1415 == double.MaxValue)
{
    ...
}

then yes you'll probably start seeing weird precision issues pop up.

The following are special constants that can't be compared to themselves. Anything else is fair game.

  • NaN
  • NegativeInfinity
  • PositiveInfinity
like image 26
Chris Eberle Avatar answered Nov 15 '22 20:11

Chris Eberle