Re: Division in C++

Antoun Kanawati <antounk@comcast.net>
12 Jul 2005 05:11:48 -0400

          From comp.compilers

Related articles
Division in C++ garms@gmx.de (Onno Garms) (2005-07-11)
Re: Division in C++ antounk@comcast.net (Antoun Kanawati) (2005-07-12)
Re: Division in C++ qrczak@knm.org.pl (Marcin 'Qrczak' Kowalczyk) (2005-07-12)
Re: Division in C++ tmk@netvision.net.il (Michael Tiomkin) (2005-07-12)
Re: Division in C++ henry@spsystems.net (2005-07-12)
Re: Division in C++ fw@deneb.enyo.de (Florian Weimer) (2005-07-12)
Re: Division in C++ gdr@integrable-solutions.net (Gabriel Dos Reis) (2005-07-12)
Re: Division in C++ qrczak@knm.org.pl (Marcin 'Qrczak' Kowalczyk) (2005-07-12)
[2 later articles]
| List of all articles for this month |
From: Antoun Kanawati <antounk@comcast.net>
Newsgroups: comp.compilers,gnu.g++.help
Date: 12 Jul 2005 05:11:48 -0400
Organization: Compilers Central
References: 05-07-046
Keywords: C++,arithmetic
Posted-Date: 12 Jul 2005 05:11:48 EDT

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



Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.