Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep an average of x numbers while still adding

Tags:

arrays

c#

I need to keep a rolling average going. I need to say have 10 numbers in an array (or something else?) and keep adding to this and get the average of those numbers.

I have a program which each second will get a number and add this to a list. I then need the average of the last x numbers in that list. Also needs to limit the amount in the list so that memory doesnt fill up as it will be adding numbers each second.

Anyone can help? I have no idea where to start

eg array 10,9,8,7,6,5,4,3,2,1 average = 5.5

add next number 11,10,9,8,7,6,5,4,3,2 average = 6.5

and so on,

the array needs to be only the last 10 numbers added to the array

like image 508
adam moore Avatar asked Dec 01 '25 04:12

adam moore


1 Answers

If you need an average of the last x numbers, make an array of x values, and use it as a circular buffer.

Keep the running total in addition to the buffer. When a new number comes in, see if your circular buffer is filled. If it is, subtract the last number from the running total before adding the newly received number.

This will let you compute the new average in O(1) time instead of O(x), i.e. the computation time will be independent of the number of items being averaged.

like image 148
Sergey Kalinichenko Avatar answered Dec 08 '25 13:12

Sergey Kalinichenko