Z
Z
zlodiak2018-02-23 17:19:46
JavaScript
zlodiak, 2018-02-23 17:19:46

Why is the average different?

Please help me understand why this code outputs the average value = 3:

var a = Rx.Observable.range(1, 5)
  .reduce((prev, curr) => {
  	return {
    	sum: prev.sum + curr,
      count: prev.count + 1
    };
  }, { sum: 0, count: 0 })
  .map(o => {
  	return o.sum / o.count;
  })
  
a.subscribe(x => console.log('avg is:', x));

And this code, displays the average value = 2:
var a = Rx.Observable.range(0, 5)
  .reduce((prev, curr) => {
  	return {
    	sum: prev.sum + curr,
      count: prev.count + 1
    };
  }, { sum: 0, count: 0 })
  .map(o => {
  	return o.sum / o.count;
  })
  
a.subscribe(x => console.log('avg is:', x));

I present how the reduce operator works in native js. But I don’t understand why in the second case, zero in the sequence changes the result so much.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-02-23
@zlodiak

The second parameter in range is the number of elements, not the final value (as you seem to think).
That is, in the first case, the sequence is: 1, 2, 3, 4, 5. And in the second, this: 0, 1, 2, 3, 4. Accordingly, 15 / 5 = 3, 10 / 5 = 2, everything is correct .

Q
qwert87, 2018-02-23
@qwert87

Look here, maybe it will help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question