Hi
Trying to create a type of low pass filter where I am constantly average the previous 10 float values. Not sure whether to use Builtin arrays (native .NET arrays), the .NET Stack operator, or perhaps an ArrayList.
In pseudocode I need to
1- Define the array or Stack containing 10 floats
2- Every update Push a new value to the Array or Stack
3- Check the length and if greater than10 remove the first or oldest float value from the Array or Stack
4- Get the average of all float values in the Array or Stack
5- Repeat steps 2-4
1st question
Should I be using built in Arrays, an ArrayList or Stack instead? I notice in the Stack documentation there is no method for removing the oldest (bottom)item from the stack, but perhaps I am missing something
2nd
Can anyone help with actual syntax using either approach? Any help appreciated!
I would just make an array of floats, then have a āroverā integer that decides where to store the next incoming data point, and it would wrap around 0-9 repeatedly.
That way you donāt have much memory allocation/deallocation, no moving stuff around or anything, just overwriting the 10th oldest value with the latest one in a circular buffer.
Your āget outputā function would just sum the array and divide by 10.
You can get clever and cache that lazily-computed result, invalidating it only when new data arrives.
You can give it a āresetā method that clears all data to zero or some other nominal value.
Another optimization would be to store the running sum of values, and when you get each datapoint, subtract out the old value, add in the new value, and then you always have the average handy with just a divide to do before you return it.
1 Like
Donāt use ArrayList. Itās almost never the option you want. A Stack is useful when you want easy access to the last item you added, which is not your use case. If anything, a Queue would be most appropriate but you would need to add the max capacity and circular behavior manually.
Kurt-Dekkerās idea sounds like the simplest in terms of implementation and memory. An implementation detail is whether to extend an existing collection, or just create a service class to provide the features you need. Personally, Iād go with a simple service class, keeping the array internal and possibly implementing the ICollection interface.
I liked the whole response, but I picked out this quote in case it related to the OPās other thread asking about getting the average every update loop. This is what I thought of posting there, before I saw this thread. This has to be the most efficient approach⦠especially now the the whole āideaā is laid out (it wasnāt in the other thread).