Different output for sum using loop w/ (k*k) or pow(k,2)

Hello, I have a problem with the output from my summation code.
I put the same equation for the sum, but whether I put k*k or pow*k,2), the outputs are different. Would you guys take a look at it, please?

The first loop using k*k,

int main()
{

float sum1 =0;

for (int k = 0; k <= 9999; k++)
{
sum1 += float(5 * k * k - 15 * k + 30) / (25 * k * k + 10 * k - 3);
}

cout << sum1 << endl;

return 0;
}
The output is 1665.85, this is NOT correct.



The second loop using pow(k,2),

int main()
{

float sum1 =0;

for (int k = 0; k <= 9999; k++)
{
sum1 += float(5 * k * k - 15 * k + 30) / (25 * pow(k,2) + 10 * k - 3);
}

cout << sum1 << endl;

return 0;
}

The output for this is 1985.2 that is correct.

I did not change anything but used pow instead of simple k*k.
I don't find the difference between them but why do they give different outputs?

I should go by with k*k for the efficiency in execution time, what should do I do to correct the output?
Your bracket is trying to do entirely integer arithmetic, but it may be exceeding the maximum size of an int. When k is 9999 that denominator is rather large. pow() would coerce it to type double, avoiding the problem.

Just change the 25 to 25.0 and you will probably solve the problem in your first code. You would be well advised to do similarly in the numerator bracket also.

Difficult to try out on an iPad because YOU HAVEN'T USED code TAGS.


BTW. I assume you know that your denominator would factorise (and you could also take a factor of 5 out of the numerator).
Last edited on
Thank you! It worked.
This should give you the same sum (to a slightly higher accuracy).

1
2
3
4
5
6
7
8
9
10
#include <iostream>
int main()
{
   double sum1 = 0;
   for ( int k = 0; k <= 9999; k++ )
   {
      sum1 += 0.2 - 10.2 / ( 5 * k + 3 ) + 6.8 / ( 5 * k - 1 );
   }
   std::cout << sum1 << '\n';
}
Topic archived. No new replies allowed.