help-gplusplus
[Top][All Lists]
Advanced

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

Re: [about optimization]Is this a bug of gcc?


From: Bernd Strieder
Subject: Re: [about optimization]Is this a bug of gcc?
Date: Fri, 15 Feb 2008 18:26:13 +0100
User-agent: KNode/0.10.4

Hello,

mojianhao wrote:

> 
> 
> Hi experts,     I have a small test case, it got different result when
> compile with -O0 option and -O2 option. Is this a bug of gcc
> ?===============================test.c===============================#include
> <stdio.h>void test(double a){  double b;  b = a * 100000.00000000000; 
> if(a<0)    printf("a<0\n");  else if(b == 19753086420000.0000000000) 
> {    a += 0.000005;    printf("a+=0.000005\n");  } 
> printf("a=%f\n",a);}int main(){  double a=987654321/5.0; 
>
test(a);}===========================================================result:=============================$
> gcc -O0 test.c$ ./a.outa+=0.000005a=197530864.200005$ gcc -O2 test.c$
> ./a.outa=197530864.200000==========================================================

At first it is a principial error in floating point arithmetic to use ==
for comparisions, because it does not give you a sensible result in
most of the cases. Look with the keyword "Floating Point arithmetic" in
the internet, e.g. Wikipedia, it should direct you to some essays one
should have read before using double. This will give you an idea of the
whole problem, and howto design your code around it. This is not
something you can solve at once for all cases, but you have to analyze
the numerical aspects of your concrete problem.

Second on ix86 processors the floating point unit has higher internal
precision than double, which makes the main difference, here. With
optimization intermediate results are kept in floating point registers
within the CPU, without optimizations they are rounded down and stored
with only double precision into some memory location, which makes the
difference. Read the docs of gcc, there are many options regarding
floating point math.

If your floating-point code is well-written, then the additional
precision of the optimized math code will not do any harm, and your
code will be easier to port to other platforms. This is the best you
can get, because there is no guarantee for extended precision at any
place. If deep in a calculation all floating point registers are in
use, the compiler will have to round some value down to double
precision and store it, to free a register. 

Bernd Strieder



reply via email to

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