Wednesday, March 25, 2009

Puzzle 9 - Solution

The key to solving this puzzle is understanding 'hardware limitation'. Floating point numbers are represented in IEEE floating point format - however floating point operation - addition, subtraction, multiplication - don't give an accurate result but always have a small error associated with them due to hardware limitation.

The for loop for(double d = 0.0; d != 1.0; d = d + 0.1) does floating point addition. However as floating point addition is not 100% accurate adding 0.1 10 times gives us a number slightly more than 1.0 (say 1.00000001). The equality condition (1.0 == 1.00000001) fails and the loop continues forever.

Key Learning

With floating point numbers it is better to use the greater-or-equal or less-or-equal operator instead of equality operator i.e. use '<=' or '=>' instead of '=='.

Sorry no correct answers this week!

No comments:

Post a Comment

Solution for this question?