Cannot Fix a calculation Error for a Sum

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;
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.
Thanks so much. That worked perfectly.

I appreciate the help!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <iomanip>
#include <limits>

template < typename FLOATING_POINT_TYPE > void g_function()
{
    std::cout << std::fixed << std::setprecision( std::numeric_limits<FLOATING_POINT_TYPE>::digits10 ) ;
    FLOATING_POINT_TYPE gsum = 0 ;
    for( int i = 1; i <= 99999999; ++i )  gsum += 1.0 / (100000000 - i);
    std::cout << "uncompensated summation: " << gsum << '\n' ;
    
    // http://en.wikipedia.org/wiki/Kahan_summation_algorithm
    gsum  = 0 ;
    FLOATING_POINT_TYPE compensation = 0 ;
    for( int i = 1; i <= 99999999; ++i )
    {
        FLOATING_POINT_TYPE term = 1.0 / (100000000 - i) - compensation ;
        FLOATING_POINT_TYPE temp = gsum + term ;
        compensation = ( temp - gsum ) - term ;
        gsum = temp ;
    }
    std::cout << "  compensated summation: " << gsum << "\n\n" ;
}

int main()
{
    g_function<float>() ;
    g_function<double>() ;
    g_function<long double>() ;
}

http://coliru.stacked-crooked.com/a/5ffb17ea4b597c47
Topic archived. No new replies allowed.