On 9 Apr., 15:26, (E-Mail Removed) wrote:

> i have encountered the strangest behavior. Check out this simple

> program:
[..]

> What would you expect to be printed:

> All the numbers from 0.0 to 0.9 with the prefex: foundXX

> and last line in output should be found 0.15 - right?!

> Wrong... what I get is all the numbers from 0.0 to 0.1 printed

> (including 0.1!!)
The number 0.1 is not representable in the internal format for double

numbers of your compiler, see for example IEEE-754. In binary format,

0.1 has a infinite length periodic mantissa:

0.1 (10) == 0.00011001100110011... (2), with a period length of four

digits. This is analog to 1/3 with base 10: 1/3 = 0,33333... (10) and

with base 3 it is just 0.1 (3), no periodic repetition.

The compiler selects the closest match it can store internally which

is off by ~10^(-1

for Visual C++ 2005. Your repeated adding of this

only-nearly-0.1 number accumulates an error that gives you the

"strange" behavior. Machine double numbers are a finite subset of the

infinite real number domain. The operations on them executed by a

computer are similar but not identical to the math +, -, *, /, ...

operators 0.1 + 0.1 + 0.1 + 0.1 + 0.1 .

You should not check identity of two doubles like in "if ( i ==

0.15 ) ...". Better define a error margin, eg:

const double eps = 1E-9;

if ( i < 0.15 + eps && i > 0.15 - eps ) ...

This will save you from some nasty surprises in real applications.

Note, you should adapt eps according to your expected accumulated

error, depending on the operations you executed before, 10^(-9) may be

to small or too large.

> When checking if ( i==0.1) { printf( "foundXX %f\n",i);} it does not

> print foundXX 0.1!!

> Why exactly does it think that 0.1 is < than 0.1!!??
Try a variation on the 2nd printf() in your code:

printf( "foundXX %20.18lf (%20.18lf)\n", i, i - 0.1 );

> Thanks
My pleasure.

Michael.