Jacek Dziedzic wrote:

John Doe wrote:
>I have a not-so-large double in the range 1-1000, but with fractional

part. I only do ++my_double to increment it, however sometimes it

happens that after incrementing

int(old_double) == int(new_double)

why? Again the doubles are not large at all, their exponents cannot

be so high to shift out the 1 I add out when incrementing and we

have 64 bits to use here.

Casting to int truncates the fractional part. Some values do

not have a finite representation in binary format and so cannot

be stored in a double with infinite accuracy. I imagine the

scenario is something like (though not for number 42):

double x=42; // actually becomes x=42.00000000000001

That is very unlikely. Integers of this magnitude are represented

precisely in IEEE floats. It could be after some kind of imprecise

calcuation, of course.

int y=(int)x; // the fractional part is truncated, y becomes 42.

x++; // actually becomes x=42.99999999999999

That is not possible. How can adding 1 screw up the mantissa so

badly? See my analysis below.

int z=(int)x; // the fractional part is truncated, z becomes 42.

z==y; // true

... but this is just guessing.

Yep.

What's going on with the number when you add 1?

Before adding the FP number can be written (in binary form) as

1bbbbbb.bbbbbbbbbbbbbB (total of N binary digits)

^^^^^^^

K digits before binary point. 'B' is the last binary digit

in the representation.

After adding 1 we could have either

10000000.bbbbbbbbbbbbbb (total of N binary digits)

^^^^^^^

K zeros

which would mean the last digit ('B') is lost or rounded to make

the fraction slightly different. If it's rounded "down", it is

the same as throwing it out. If it's rounded up, you can end up

with a fraction that when rounded eventually turns into another 1

and is added to the integral part (for that you need the fractional

part full of 1s). In either case adding 1 cannot mean retaining

the integral part (it either grows by 1 or by 2).

We could have (after adding 1)

1bbbbbb.bbbbbbbbbbbbbB (total of N binary digits)

^^^^^^^

K (slightly different) digits before binary point. 'B' is

still the last binary digit, in which case the fraction does not

change at all, and simply cannot contribute to changing the

integral part.

V

--

Please remove capital 'A's when replying by e-mail

I do not respond to top-posted replies, please don't ask