1

Why are these two snippets of code giving two different results?

    double sum = 1.0;
    double xSqFour = x * x / 4;

    for (int i = 48; i > 1; i-=2) {
        sum = 1.0 + (xSqFour / ((i/2) * (i/2))) * sum;
    }

    return sum;

and

    double sum = 1.0;
    double xSqFour = x * x / 4;

    for (int i = 24; i > 1; i--) {
        sum = 1.0 + (xSqFour / (i * i)) * sum;
    }

    return sum;
yodie
  • 431
  • 5
  • 14

1 Answers1

3

You have a bounds error on your second loop. It should be i > 0. The first loop has i > 1, but it also divides i by 2. 1 / 2 == 0, so it should be i > 0 in the second loop.

Omnifarious
  • 54,333
  • 19
  • 131
  • 194
  • Gee, thanks! (I'm headdesking now, as that should've been obvious.) Will accept in 5 minutes. – yodie Oct 17 '10 at 02:41
  • It's purely a bounds thing, and has nothing to do with the `i/2` bit, the OP is decrementing by 2 in the first instance; here's an example of what's going on: http://ideone.com/uIqDI – Mark Elliot Oct 17 '10 at 02:44