help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Division in C++


From: Antoun Kanawati
Subject: Re: Division in C++
Date: 12 Jul 2005 05:11:48 -0400

Onno Garms wrote:
> Hello,
>
> I have a short sample program that hangs on one of my
> computer when I compile in debug mode. The program works
> fine on my other computers or if I compile optimized.
>
> The problematic computer and compiler are quite old (gcc2.95
> on a Pentium PC running Linux), but I wonder if the problem
> will occur with other compilers on other computers if I
> change the numbers.
>
> Here is the code:
>
> int main ()
> {
>   double a = 96.03755458500125997;
>   double b = 3.0;
>   double c;
>
>   while (1)
>   {
>     c = a/b;
>     if (a/b<=c) break;
>   }
> }

The floating point registers are 80-bits wide, while 'double' is 64-bits
wide.  If you compile, without optimization, the variable 'c' holds
the result of division, truncated to 64-bits.  So, in the conditional
the following happens:

        repeat the division, and hold the 80-bits result
        load the value of 'c' and extend to 80-bits
        compare the above two values.

Since 'c' was truncated to 64-bits and then extended to 80, it will
appear to be smaller than the untruncated result, and the comparison
fails.

However, if you swith to 'long double', you get sufficiently many bits
stored in 'c', and the program behaves are you expected.

BTW, using gcc 3.4.2 with -O3 on the above program, you get a main
function that does nothing:

main:
..LFB2:
        pushl   %ebp
..LCFI0:
        movl    %esp, %ebp
..LCFI1:
        subl    $8, %esp
..LCFI2:
        andl    $-16, %esp
        subl    $16, %esp
        xorl    %eax, %eax
        leave
        ret
--
A. Kanawati
NO.antounk.SPAM@comcast.net



reply via email to

[Prev in Thread] Current Thread [Next in Thread]