Sum of rows using float

I calculated the first 20 elements of the series -

enter image description here

in two ways, 1 - forward, 2 - backward. For this I did -

#include <iostream>
#include <math.h>
using namespace std;

float sumSeriesForward(int elementCount) {
    float sum = 0;
    for (int i = 0; i < elementCount; ++i) {
        sum += (float) 1 / (pow(3, i));
    }
    return sum;
}

float sumSeriesBack(int elementCount) {
    float sum = 0;
    for (int i = (elementCount - 1); i >= 0; --i) {
        sum += (float) 1 / (pow(3, i));
    }
    return sum;
}

int main() {
    cout.precision(30);
    cout << "sum 20 first elements - forward: " << sumSeriesForward(20) << endl;
    cout << "sum 20 first elements - back: " << sumSeriesBack(20) << endl;
}

And I got -

sum 20 first elements - forward: 1.5000001192092896
sum 20 first elements - back: 1.5

Can someone explain why the difference is between the two ways?

+5
source share
2 answers

. . , , . , , , . , .

, . , 4 :

values   top to bottom   bottom to top
10.00      10.00            10.01
0.004      10.00            0.010
0.003      10.00            0.006
0.002      10.00            0.003
0.001      10.00            0.001

, [] .

+10

, Kahan. ( ).

+5

All Articles