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;
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.