Is it possible to calculate an average number without a finite set of numbers?

144 Views Asked by At
Starting At 12:00:00  I have 0 items
         At 12:00:10  I have 488 items
         At 12:00:20  I have 971 items
         At 12:00:30  I have 1532 items
         At 12:00:40  I have 2103 items

More items are added continuously and reported every 10 seconds. Is it possible to calculate the average number of items per minute, second and hour when the number of items may never stop accumulating?

1

There are 1 best solutions below

0
On BEST ANSWER

Given a programming context with a function input() that is called to get each successive reading from some external source, then mean = w * input() + (1-w)*mean will compute a running mean of the input values. Where w is a weight between 0 and 1. When w=1, the mean is set to the immediate value of the input. For w=0 it remains unchanged at its initial value. For w=0.5, for example, it will be an exponentially weighted mean of the previous values in the sequence.

If you literally need the unweighted arithmetic mean then you need to keep a counter:

c=1
m=input()

repeat:
  m = c * m + input()
  c = c + 1
  m = m/c

This is really just a way of keeping the sum of all the inputs and the count of all the inputs, and noting that the ratio is the mean. The method above has more operations, but keeps the stored values from drifting in a typical context.

Floating point error would typically take its toll of course.