views:

89

answers:

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;
+3  A: 

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
Gee, thanks! (I'm headdesking now, as that should've been obvious.) Will accept in 5 minutes.
yodie
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 E
@Mark - Oh, my first intuition was right. *sigh* Oops.
Omnifarious