473,473 Members | 2,122 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

finding the nth value

Hi, still very new to programming but am a little stumped by how to do this
idea i have.

I need to make a moving average which takes every nth value in a data series
to build a running total which can then be divided by the length of the
moving average. The data series will be gaining a new value every x amount of
time t so the average has to be made from the last added value. And i also
need a way to use this same moving average but from different start point ie
t-1, t-2 etc What is the best way to do this?

Any help would be greatly appreciated.
Sep 22 '07 #1
4 2247
Hi,

Try this:

------- CODE TO PASTE IN VS ------
public class AvgSerie
{
List<int_InnerData = new List<int>();

/// <summary>
/// Appends a new value to the serie
/// </summary>
/// <param name="value">new value</param>
public void AddValue(int value)
{
_InnerData.Add(value);
}

/// <summary>
/// gets the last n-sized average
/// </summary>
/// <param name="length">n-size value</param>
/// <returns></returns>
public int GetLastMovingAverage(int length)
{
return GetMovingAVG(_InnerData.Count - length, length);
}

/// <summary>
/// Retrieve a moving average
/// </summary>
/// <param name="startindex">0 based index of the first measure
to use</param>
/// <param name="length">Number of measures to use</param>
/// <returns></returns>
public int GetMovingAVG(int startindex, int length)
{
int response = 0;
int stopindex = startindex + length-1;
if (stopindex <= _InnerData.Count)
{
for (int i = startindex; i <= stopindex; i++)
{
response += _InnerData[i];
}
response /= length;
}
else
{
throw new Exception("The index provided exceeds the
size of the serie");
}
return response;
}
}

------- END OF CODE TO PASTE IN VS ------

b1uceree wrote:
Hi, still very new to programming but am a little stumped by how to do this
idea i have.

I need to make a moving average which takes every nth value in a data series
to build a running total which can then be divided by the length of the
moving average. The data series will be gaining a new value every x amount of
time t so the average has to be made from the last added value. And i also
need a way to use this same moving average but from different start point ie
t-1, t-2 etc What is the best way to do this?

Any help would be greatly appreciated.
Sep 22 '07 #2
b1uceree wrote:
Hi, still very new to programming but am a little stumped by how to do this
idea i have.

I need to make a moving average which takes every nth value in a data series
to build a running total which can then be divided by the length of the
moving average. The data series will be gaining a new value every x amount of
time t so the average has to be made from the last added value.
If you want the moving average to be exactly the average of the last N
samples, you need to save N samples, dropping one off the end when you
add a new one to the beginning.

For example:

const int kcvalueMoving = 20;
double valueTotal = 0;
Queue<doublevaluesPrevious = new Queue<double>(kcvalueMoving);

double MovingAverage(double valueNew)
{
if (valuesPrevious.Count == kcvalueMoving)
{
valueTotal -= valuesPrevious.Dequeue();
}

valueTotal += valueNew;
valuesPrevious.Enqueue(valueNew);

return valuesTotal / valuesPrevious.Count;
}

If you don't want to keep track of all the previous values, you can just
keep the sum, adding a weighted value to it with each iteration. As
each iteration weights the previous sum at less than 100%, trailing
values will become less and less significant. However, it's not exactly
a moving average and you'll have to watch out for the divisor (count of
samples) eventually reaching the maximum the variable can contain.

IMHO, if you want a true moving average, the code above is probably want
you want.
And i also
need a way to use this same moving average but from different start point ie
t-1, t-2 etc What is the best way to do this?
I'm not exactly clear on this part of your requirement. If you have to
be able to arbitrarily pick any point in the sequence of data and return
a moving average based on that sequence, you will have to save _all_ of
the samples in the sequence of data, and then simply perform a regular
average of the previous N elements for a given position within the sequence.

If you have this requirement and the number of samples for a given
moving average is relatively small (less than a hundred or so, for
example), then you may not want to bother with the implementation I
included above. It's slower to recalculate the average from scratch
each time, but if you have to do that anyway in some cases, you might as
well keep the code simple and just have a single implementation that
works for both scenarios.

If you have a known subset of "different start points", then you could
just cache the result of the primary moving average calculation. For
example, if you always only want to allow access to the last M averages,
you could keep a list of length M. There are a number of ways you could
implement this while allowing both easy adding of new averages and
removal of old ones, while still having access to all of the averages:
* You could use an actual LinkedList and enumerate when you need a
specific entry,
* You could use the Queue class and use the ToArray() to get at a
specific entry within the Queue, or
* You could use a different queue implementation (Jon Skeet has a
RandomAccessQueue that would serve this purpose nicely, in his MiscUtil
library: http://www.yoda.arachsys.com/csharp/miscutil/)

If you mean something different, then perhaps you could clarify.

Pete
Sep 22 '07 #3
Both Martin and Peter have provide answers so that you get the average of the
last N entries in your list, which can be added to as data comes into the
list. It appeared to me that you were asking a slightly different question,
which was that the list grows, but to step through the list as the index
increases by N. For example, if the list is size 10, and N = 2, you want the
average of list [0, 2, 4, 6, 8]. If this is what you want, then your average
routine would be something like this:

public double RunningAverage(List<doubleAllData, int StartIndex, int
StepSize)
{
int DataPoints = 0;
double Sum = 0.0;

for(int Index = StartIndex; Index < AllData.Count; Index += StepSize)
{
Sum += AllData[Index];
++DataPoints;
}

if (DataPoints == 0) return 0;
return (Sum / (double) DataPoints);
}

"b1uceree" wrote:
Hi, still very new to programming but am a little stumped by how to do this
idea i have.

I need to make a moving average which takes every nth value in a data series
to build a running total which can then be divided by the length of the
moving average. The data series will be gaining a new value every x amount of
time t so the average has to be made from the last added value. And i also
need a way to use this same moving average but from different start point ie
t-1, t-2 etc What is the best way to do this?

Any help would be greatly appreciated.
Sep 22 '07 #4
Thanks Mike, Martin and Peter,

You have all given me good ideas to structure the code and you are correct
Peter in pointing out that it is in effect a picking 0,2,4,6,8 at time t and
1, 3, 5, 7, 9 at t+1 but what i didnt explain correctly is that there will be
first a simple moving average then i will be taking a moving averages using
the step through approach. These basically the first two steps that you need
to take in creating a time adjusted or seasonal moving average.

"Family Tree Mike" wrote:
Both Martin and Peter have provide answers so that you get the average of the
last N entries in your list, which can be added to as data comes into the
list. It appeared to me that you were asking a slightly different question,
which was that the list grows, but to step through the list as the index
increases by N. For example, if the list is size 10, and N = 2, you want the
average of list [0, 2, 4, 6, 8]. If this is what you want, then your average
routine would be something like this:

public double RunningAverage(List<doubleAllData, int StartIndex, int
StepSize)
{
int DataPoints = 0;
double Sum = 0.0;

for(int Index = StartIndex; Index < AllData.Count; Index += StepSize)
{
Sum += AllData[Index];
++DataPoints;
}

if (DataPoints == 0) return 0;
return (Sum / (double) DataPoints);
}

"b1uceree" wrote:
Hi, still very new to programming but am a little stumped by how to do this
idea i have.

I need to make a moving average which takes every nth value in a data series
to build a running total which can then be divided by the length of the
moving average. The data series will be gaining a new value every x amount of
time t so the average has to be made from the last added value. And i also
need a way to use this same moving average but from different start point ie
t-1, t-2 etc What is the best way to do this?

Any help would be greatly appreciated.
Sep 24 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Steve | last post by:
Hi, I have a very long string, someting like: DISPLAY=localhost:0.0,FORT_BUFFERED=true, F_ERROPT1=271\,271\,2\,1\,2\,2\,2\,2,G03BASIS=/opt/g03b05/g03/basis,...
3
by: Jorn W Janneck | last post by:
hello everyone. i have the sort of question that makes me feel like i am missing the forest for the trees, so apologies if i am missing the blatantly obvious here. i am using saxon, and mostly...
5
by: Mike | last post by:
Hi I've written a module to find the first occurrence of a record in a query (that is my forms datasource) that matches four specified criteria. No matter what I try it doesn't seem to find ...
1
by: Doug | last post by:
The html below shows DataList "DiscountList" nested within DataList "EventItemList". DiscountList contains a Label control. I'm trying to find the label, using FindControl, during...
2
by: ElkGroveR | last post by:
Hi there! I'm using PHP to create a simple, dynamic MySQL SELECT query. The user chooses a selection from a HTML Form SELECT element's many options and submits the form via a POST action. ...
3
by: HEMH6 | last post by:
Who can help solve this problem??? Finding the Largest Value (a) write a function, largest(), that returns the largest value in a signed integer array. The array and its size are passed as...
1
by: Mike Heywood | last post by:
Hi, I am currently trying to automate a process that I have been studying the manual results from for a while. The process simply identifies events that meet certain criteria and at the moment...
17
by: NetworkElf | last post by:
Hi all, I'm writing a service that needs to discover the full directory path for a given locally based share at startup. IOW, I need to have the service running on someserver to take ...
13
by: spicster | last post by:
I need help with finding an entire inventory value for a java assignment. This is what I have so far. I am new to Java and am struggling. In need of help, thanks import...
275
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.