Wednesday, June 06, 2007

Odd GCC Optimization Issue

I am working on a modification to some C code for a customer, and stumbled upon an odd problem with the GNU C Compiler (gcc version 4.0.3-1ubuntu5). The code computes payments and amortization schedules for requested loans, and returns the information in data structures.

I noted the problem when writing a payment stream generator (e.g. "x payments of $a", "y payments of $b", etc.). With optimizations turned off, the payment stream was being output correctly for the loan in questions (2 payments of $47.26 followed by 4 payments of $2530.39).

However, once I turned on optimization (-O2), the payment stream gave me a hiccup and reported: 1 payment of $47.26, 1 payment of $47.26, 4 payments of $2530.39.

Hmmm - odd. Printing out the first two payments to 15 decimal places revealed an extremely slight difference (47.259999999999998 vs. 47.260000000000005), even though the two values are computed using the same factors, rounded in the same manner, etc.

I wish I could reduce the code to something simple for demonstration purposes, but the code is extremely complex and has many dependencies on other units, so it would not be a trivial matter to say the least.
For now, I have replaced the -O2 optimization flag with the following: "-finline-functions -floop-optimize -falign-functions -falign-loops -funroll-loops". With those optimization options turned on, the results are as expected.

I just checked to see if the same issue occurred with an older version of gcc (version 3.3.5 Debian Sarge) and the same problem does appear. Odd.

No comments:

Post a Comment