Monday, March 10, 2008

This is a loop that never ends - it just goes on and on my friends!

for (double d = 0.0; d != 1.0; d += 0.1)



David said...

everybody's favourite compiler docs:

Warn if floating point values are used in equality comparisons.

The idea behind this is that sometimes it is convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If you are doing this, then you need to compute (by analyzing the code, or in some other way) the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but that's a different problem). In particular, instead of testing for equality, you would check to see whether the two values have ranges that overlap; and this is done with the relational operators, so equality comparisons are probably mistaken.

this page solutions in more depth.

Hacky said...

The only fractions you can represent in floating point accurately are of the form (X/(2^n)).

For example 0.5, 0.25, etc. 0.1 does not simplify to this form so it can not be represented exactly.

As soon as you've done any operation with any other number, your results will have some error due to the precision of the representation.

It gets worse when you deal with custom processors with non-standard FPU cores that haven't been validated as thoroughly as your mainstream processors. For example, on the Sony PS2 (you can try this with PS2 Linux if you like), (X * 1.0f) == (1.0f * X) is not true for quite a few values of X due to internal rounding issues!

dzembu said...

well... there are many loops that never ends. It is also not likely a mistake a beginner will make: most loops garded by < or <= not ==. There are a lot of mistakes beginner will make comparing floats and doubles, but ... the first time some one will explain this it back to track. Most companies define a library macro that compare two floats with some level of tolerance. So... if such macro or function will be used for this funny float numbers in C ... this loop will end as expected. Hm... I feel I miss the point of this post. It must be funny, right ?

Eldar said...

Dzembu is optimist... 0.25 in a binary system...? Good thing, he's escaped grasps of evil group and going to be free by April.