0

I'm trying to calculate a simple approximation to an integral by dividing it up into a step function, easy stuff. The problem starts when I simply try to do a division. Here is my code:

double integrand(int a, double div, int n) {
    int i;
    double sum, val;

    val = 1.0/div;

    for(i = 0; i < div; i++) {
        sum = sum + (pow(i*val, n)/(i*val + a)) * val;
    }
    return sum;
}

Here div is actually an integer, I tried bringing it into the integrand function originally as an integer and typecasting it to a double inside the function, with the same result. When I debug the code, div can be say, 100, yet val will return something ludicrous like -7.2008557565654656e+304. As far as I'm aware the rest of the code is correct, but I just cannot figure this out, what's going on?!

  • possible duplicate of [Strange result of division in C](http://stackoverflow.com/questions/985601/strange-result-of-division-in-c) – Daniel A. White Nov 20 '13 at 16:59
  • 1
    I've already considered the possibility of floating point inaccuracies, but I didn't expect an arbitrarily enormous result for 1 /100.. – user3014043 Nov 20 '13 at 17:05
  • This `val = 1.0/div;` gives you something like `-7.2008557565654656e+304` for `val`? – alk Nov 20 '13 at 17:05
  • 1
    Did you try to remove that loop that makes use of "unitialised sum" and just print the value of val=1.0/div? it should just be 0.01 – Jekyll Nov 20 '13 at 17:11
  • @DanielA.White: This does not seem to be a duplicate of what you linked. – alk Nov 20 '13 at 17:11
  • Log `div` prior to taking the reciprocal (1/x), perhaps is not receiving what you think it would. Did you ran this in a debugger and inspected the values? – alk Nov 20 '13 at 17:13
  • No, `div` is not actually an integer. It will be promoted to a `double` at the call site before entering your function - you may actually be calling the function with an integer, but the compiler will make sure that by the time that `div` exists in your function, it will have been converted. – twalberg Nov 20 '13 at 17:27

2 Answers2

2

You never initialized sum:

double sum = 0, val;

Right now, you're using it in your calculation with an uninitialized value, and hence getting some garbage results.

FatalError
  • 52,695
  • 14
  • 99
  • 116
  • Feel like an idiot now, it seems not giving sum an initial value was screwing with val, it assigns just fine now. Apologies for a crap question. – user3014043 Nov 20 '13 at 17:11
  • 1
    @user3014043: No worries, we've all been there, and more often than we'd like to admit ;). – FatalError Nov 20 '13 at 17:17
1

First initialize sum and then use it. Otherwise it will invoke undefined behavior.

haccks
  • 104,019
  • 25
  • 176
  • 264