# The sum that does not equals the sum. gdb involved.

• 05-31-2012
nepper271
The sum that does not equals the sum. gdb involved.
Hello everyone,

I'm having a very strange problem with my code. In an assignment, the right hand is a sum, that I verify using gdb. The left side does not take that value. Instead, it takes the rounded value. Given that the values are doubles, I wasn't expecting a round up.

The following code is what I run with gdb:
Code:

```54              for (Int i = 0; i < nvar; i++) (gdb) 55                xx[i] = xcx[i] + dx[i]; (gdb) 54              for (Int i = 0; i < nvar; i++) (gdb) print xcx[0] \$1 = 0.49999999998343619 (gdb) print dx[0] \$2 = 1.6563789318635447e-11 (gdb) print i \$3 = 0 (gdb) print xcx[0]+dx[0] \$4 = 0.49999999999999994 (gdb) print xx[0] \$5 = 0.5```
Unfortunately the project is too big and has too many dependencies.
• 05-31-2012
Salem
Welcome to the weird world of floating point numbers.

Given that floats are approximate to begin with, I see nothing strange between
(gdb) print xcx[0]+dx[0]
\$4 = 0.49999999999999994
(gdb) print xx[0]
\$5 = 0.5

\$4 is all nines down to the 15th digit, which means the trailing "94" is almost certainly noise anyway.
• 05-31-2012
nepper271

But shouldn't gdb round it up too? Also, when I manually set the number to the sum using gdb, it works. And the rest of the program runs normally.
Code:

```(gdb) print xx[0] \$1 = 0.5 (gdb) print xcx[0] + dx[0] \$2 = 0.49999999999999994 (gdb) print (double)(xcx[0] + dx[0]) \$3 = 0.49999999999999994 (gdb) print (float)(xcx[0] + dx[0]) \$4 = 0.49999997 (gdb) print (double)(xcx[0]) + (double)(dx[0]) \$5 = 0.49999999999999994 (gdb) set xx[0]=xcx[0]+dx[0] (gdb) print xx[0] \$6 = 0.49999999999999994```
I'm programming an interior point method, and my upper bound in the first variable is 0.5. With this round up, the method fails, because it can't touch the bound. After setting xx[0], the method goes all the way to the end.

Also, if it is indeed a rounding problem, how can I prevent it?

I tried this:
Code:

```for (Int i = 0; i < nvar; i++) {   if (xcx[i] + dx[i] == bux[i])     xx[i] = bux[i] - dciTiny;   else     xx[i] = xcx[i] + dx[i]; }```
but it didn't work.

Thanks
• 05-31-2012
QuantumPete
You can't compare floats/doubles directly. Like Salem already said they are inaccurate by definition. Instead do a comparison via an epsilon value. I.e. If the difference between the lhs and rhs is less than some value (0.0001 for example - dependson your accuracy needs) then the values are considered equal.
• 05-31-2012
nepper271
Since I know that xcx[i] + dx[i] < bux[i], I decided to make small values of dx to be equal to zero. Thank you for the replies.