473,749 Members | 2,402 Online
Bytes | Software Development & Data Engineering Community
+ 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 2260
Hi,

Try this:

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

/// <summary>
/// Appends a new value to the serie
/// </summary>
/// <param name="value">ne w 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 GetLastMovingAv erage(int length)
{
return GetMovingAVG(_I nnerData.Count - length, length);
}

/// <summary>
/// Retrieve a moving average
/// </summary>
/// <param name="startinde x">0 based index of the first measure
to use</param>
/// <param name="length">N umber of measures to use</param>
/// <returns></returns>
public int GetMovingAVG(in t startindex, int length)
{
int response = 0;
int stopindex = startindex + length-1;
if (stopindex <= _InnerData.Coun t)
{
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<doubleval uesPrevious = new Queue<double>(k cvalueMoving);

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

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

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
RandomAccessQue ue 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<doubleAllD ata, 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<doubleAllD ata, 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
3000
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, GAMESS=/opt/gamess,GAUSS_ARCHDIR=/opt/g03b05/g03/arch, GAUSS_EXEDIR=/opt/g03b05/g03/bsd:/opt/g03b05/g03/private:/opt/g03b05/g
3
4967
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 xslt version 1.1 (the unofficial one). i have a template parameter, say v, which contains a sequence of nodes of the same kind, say A, which all have an attribute, say n. these attributes may have different numeric values. i have identified the...
5
4388
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 records even though they are in the recordset as you can navigate to them using the forms navigation buttons. weekending, weekday, ba (business area), projected Here's the module can anyone spot where i'm going wrong? Any suggestions would be...
1
3184
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 EventList_ItemCreated (below the html), but it's always <undefined value> (null). Everything else works fine. Eventually I need to set the value of the label depending up the Count of the DataView "dvDiscount". For now I'll settle for just finding the damn...
2
2851
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. The SELECT query is built as follows: $itemtype = stripslashes(trim($_POST));
3
3949
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 arguments. (b)Write a main program that inputs MAX values from the keyboard into a signed integer array, array, and points, using largest(), the largest value to the screen.
1
2334
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 it then requires human interaction to decide what to do next (is a seperate process run or not). I have set up the process to do this automatically based on a couple of variables calculated but I am having a few problems optimising the data to...
17
1852
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 \\someserver\someshare and give me c:\somedir\somedir\shareddir. I'm not quite sure where to start reading about how to do this. Could someone give me a push in the right direction, please?
13
1541
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 java.util.Scanner;//program uses class scanner public class ProductInventory1 {//main method begins java application public static void main (String args)
275
12346
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
8997
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9389
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6801
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6079
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4709
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3320
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 we have to send another system
2
2794
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2218
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.