Mar 10, 2014 at 3:58pm UTC
This is a project for my first C++ college class. I have correctly calculated the first sum of the F series to be 15.403683.
However, the second series, G , is supposed to have a sum of 18.997896, and my build gets 18.807919.
Can anyone see an error in my G code for the sum?
Thanks in advance.
-----------------------------------------
// Variable Declarations
int i = 0;
int n = 100000000;
float sum = 0;
float gSum = 0;
float fsumDouble = 0;
float gsumDouble = 0;
// F FUNCTION
clock_t startTime = clock();
for( i = 1; i <= n; i++ )
{
sum += 1.0 / i;
}
cout.precision(8);
cout.fixed;
cout << "f Series: " << endl;
cout << "Float Time Elapsed : " << ((double)clock()-startTime)/CLOCKS_PER_SEC << endl;
cout << "Float Sum : "<< sum << endl;
// G FUNCTION
startTime = clock();
for( i = 1; i <= 99999999; i++ )
{
gSum += 1.0 / (100000000 - i);
}
cout.precision(8);
cout.fixed;
cout << "g Series: " << endl;
cout << "Float Time Elapsed : " << ((double)clock()-startTime)/CLOCKS_PER_SEC << endl;
cout << "Float Sum : "<< gSum << endl;
cout << endl;
Mar 10, 2014 at 4:12pm UTC
Because of floating point precision problems. It can reliably store values with ~6 digits of precision. And rounding errors will pile up. Change type to double.
Mar 10, 2014 at 5:06pm UTC
Thanks so much. That worked perfectly.
I appreciate the help!