Last time I challenged you to find a value which does not round correctly using the algorithm
Math.Floor(value + 0.5)
The value which does not round correctly is the double
0.49999999999999994, which is the largest double that is smaller than
0.5. With the given algorithm this rounds up to
1.0, even though clearly
0.49999999999999994 is less than one half, and therefore should round down.
What the heck is going on here?
The intention of this method is to round a double to the nearest integer. If the double is exactly half way between two integers then it rounds to the larger of the two possibilities:[1. For negative numbers, -1.5 should round to -1.0, since -1.0 is larger than -2.0; I do not mean larger in the sense of absolute magnitude. That would be characterized as “midpoint rounding away from zero”.]
static double MyRound(double d)
return Math.Floor(d + 0.5);
Is it correct? Can you find a value for which it does not give the mathematically correct value?[2. HINT: The value I’m thinking of is small.]
UPDATE: The answer is in the comments, so if you don’t want spoilers, don’t read the comments.
Next time on FAIC: The answer, of course.
Occasionally when I’m debugging the compiler or responding to a user question I’ll need to quickly take apart the bits of a double-precision floating point number. Doing so is a bit of a pain, so I’ve whipped up some quick code that takes a double and tells you all the salient facts about it. I present it here, should you have any use for it yourself.[1. Note that this code was built for comfort, not speed; it is more than fast enough for my purposes so I’ve spent zero time optimizing it.]