The trouble with Doubles

February 6th, 2006

If you’ve ever wondered why many developers recommend you ALWAYS use the slow, heavy Decimal type, rather than Double when doing financials, check this out:

Watching Doubles

In our production environment we’ve gotten occasional bugs that could only be the result of double.Equals failing and, as you can see, this can actually happen. .Net optimizes double performance by taking advatage of the extended floating point facilities of the processor. Thus operations done in cpu cache may be done with a higher precision than that supported by System.Double. So when you get to a point where a comparison occurs between a number in cache and one in memory, even if they were the result of the same operation, the may not be actually equal.

Unless you absolutely can’t stand the performance hit, I would recommend using System.Decimal for operations that rely on a single standard of precision across all operations.

For more on the pitfalls of .Net floating point math go here.

2 Responses to “The trouble with Doubles”

  1. Luke Flemmer Says:

    The performance hit is rather grievous though.

    Alternatively, you can just use an epsilon value in your equality comparison:

    if (Math.Abs(x – y)

  2. Damien Morton Says:

    The characterisation of the errors in floating point compuations is a whole study in and of itself.

    The long and short of it is that floating point computations arent totally precise, and may not even be deterministic (i.e. the same computation producing the same results each time).

    Basically, you should never be comparing floating point values for equality. In fact, I would go so far as to say that such a comparison should be an error in any language.

    Strangely enough, I just tried this in Whidbey and am finding that I am getting absolutely precise results.