3

When I run the following program:

#include <stdio.h>
#include <math.h>

int main()
{
    double sum, increase;
    long amount, j;

    printf("sum = ");
    scanf("%lf", &sum);
    printf("increase = ");
    scanf("%lf", &increase);
    printf("amount = ");
    scanf("%ld", &amount);

    for (j = 1; j <= amount; j++)
    {
        sum += increase;
    }

    printf("%lf\n", sum);

    return 0;
}

I obtain the following response for these values:

MacBook:c benjamin$ ./test
sum = 234.4
increase = 0.000001
amount = 198038851
432.438851
MacBook:c benjamin$ ./test
sum = 234.4
increase = 0.000001
amount = 198038852
432.438851
MacBook:c benjamin$ ./test
sum = 234.4
increase = 0.000001
amount = 198038853
432.438852

where I have increased the variable 'amount' by 1 in each case.

  • In the first one, the summation gives what I expect.
  • In the second, it surprisingly gives the same value.
  • In the third, it goes on summing.

Why does this happen?

Although the code doesn't seem to be very useful, I have just written the part in question. I actually wanted to use it in a larger program.

Thanks!

sarnold
  • 102,305
  • 22
  • 181
  • 238
Benjamin
  • 29
  • 2
  • Did you forget the actual question? – Michael Lorton May 21 '12 at 23:11
  • 6
    Floating point numbers have limited precision, and I would somewhere enough precision is lost that the amount comes out the same. – Corbin May 21 '12 at 23:11
  • 3
    What Every Computer Scientist Should Know About Floating-Point Arithmetic -- http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – epatel May 21 '12 at 23:13
  • 1
    I'm tempted to vote to close this as a duplicate of [C - Summation with double precision](http://stackoverflow.com/questions/7754590/c-summation-with-double-precision), because it's pretty much the same. The only reason I'm not is because the code in the linked question is of such poor quality, and yours is at least readable and concise. :) – Ken White May 21 '12 at 23:19

1 Answers1

3

This is an issue with the formatting, not the number. If you change printf to

printf("%.12lf\n", sum);

the results look more along the lines of what you've expected:

sum = increase = amount = 432.438851000198
sum = increase = amount = 432.438852000198
sum = increase = amount = 432.438853000198

The "junk" at the end is due to the limited precision of floating point numbers.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523