473,763 Members | 7,622 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need a queue in C

ern
I need a FIFO queue of size 20, to keep track of a running average.
Once the queue is full with 20 values, I want to take the sum/20 =
AVERAGE. Then when a new value comes in, I want:

(Old Sum - oldest value + newest value)/20 = New Average

Anybody know an efficient way to implement that? Is a queue even the
best way?

Thanks,

Jan 13 '06 #1
19 6253
ern wrote:
I need a FIFO queue of size 20, to keep track of a running average.
Once the queue is full with 20 values, I want to take the sum/20 =
AVERAGE. Then when a new value comes in, I want:

(Old Sum - oldest value + newest value)/20 = New Average

Anybody know an efficient way to implement that? Is a queue even the
best way?


This doesn't really seem like a C question, since the question would
be the same for just about any programming language. It sounds more
like a data structures and algorithms question. Or maybe a homework
question.

Having said that, I wouldn't use a queue for this unless you have a
queue implementation already done that you can use. The reason is,
since it has a fixed size known at compile time, you don't need to
handle the complexity of having a data structure that can have a
variable number of values in it.

Therefore, I would use a very simple data structure and I would have
a statement in my program that looks like this:

index = (index + 1) % 20;

- Logan
Jan 13 '06 #2
ern

Logan Shaw wrote:

This doesn't really seem like a C question, since the question would
be the same for just about any programming language. It sounds more
like a data structures and algorithms question. Or maybe a homework
question.
uhhh... it kind of IS a C question since C doesn't support std::queue.
It's not a homework question... it's actually more of an embedded
systems question, since I'm taking values of floating point current
(analog -> digital). The values are fluctuating, so I need to
implement something to stabilize the output. Right now, I'm using
qsort and taking the median. This is working great, but it's slowing
down my application a lot.
since it has a fixed size known at compile time, you don't need to
handle the complexity of having a data structure that can have a
variable number of values in it.
Wouldn't you just create a data structure that doesn't have variable
size to avoid this?
Therefore, I would use a very simple data structure and I would have
a statement in my program that looks like this:
What would that data structure look like? It doesn't really help to
say "very simple data structure."
index = (index + 1) % 20;


yeah... i know that much...

Jan 13 '06 #3
On 2006-01-13, Logan Shaw <ls**********@a ustin.rr.com> wrote:
ern wrote:
I need a FIFO queue of size 20, to keep track of a running average.
Once the queue is full with 20 values, I want to take the sum/20 =
AVERAGE. Then when a new value comes in, I want:

Therefore, I would use a very simple data structure and I would have
a statement in my program that looks like this:

index = (index + 1) % 20;

This looks similar to a circular array queue.
A queue doesn't have to be implemented using dynamic allocation
does it?
Then again, maybe this is an assignment and ern needs dynamic
allocation. :-)

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Jan 13 '06 #4
ern
What would a circular array queue look like ?

It's not an assignment !!! arghhhhhh

Jan 13 '06 #5
ern wrote:
I need a FIFO queue of size 20, to keep track of a running average.
Once the queue is full with 20 values, I want to take the sum/20 =
AVERAGE. Then when a new value comes in, I want:


You might want to look at what's available here.

http://c.snippets.org/browser.php

Brian
Jan 14 '06 #6

ern wrote:
I need a FIFO queue of size 20, to keep track of a running average.
Once the queue is full with 20 values, I want to take the sum/20 =
AVERAGE. Then when a new value comes in, I want:

(Old Sum - oldest value + newest value)/20 = New Average

Anybody know an efficient way to implement that? Is a queue even the
best way?

Thanks,


This is not really a c question other than that happens to be the
language you are using but Iwould probably just use an array of 20
elements and maintain the index to the oldest element:

//pseudocode
//some initialization stuff comes first
sum = sum - array[oldest element] + new value
average = sum / array size

array[oldest element] = new value

if oldest element is not last element
oldest element++
else
oldest element = 0

Keep in mind this is off the top of my head and is not c code. The c
code to do this should be straight forward and not much different than
my psuedocode with some additional setup and storing the right
variables in the right places but the best way for you to do that for
maximum performance really depends on your system, i.e. maybe you have
some HW registers you can use or something like that.

Jan 14 '06 #7
ern wrote:
What would a circular array queue look like ?

It's not an assignment !!! arghhhhhh

<OT>
It seems that I missed your post on my default server.
I saw it on a different server at work. I'm now curios to
see whether it will eventually show up on the default
server
</OT>

I learned about it as a "circular array queue", or "queue implemented
using a circular array". I also found it under the name of "circular queue".
It's, basically, a way to implement fixed length queues using arrays (not
only fixed length, but it's usually used when either the number of total
elements is small or you know that you will fill a large part of it all
the time
otherwise it can be a waste of space, if you have no idea how many objects
you can have in the queue at any given time).

A circular array is the one where the first element follows the last
element and
a position is calculated using modulo size of queue. You need two pointers
(meaning indices, not real pointers) to indicate the position of the
head and of
the tail. The problem is determining when the queue is empty and when it's
full as both cases would be indicated by both head and tail indices
pointing to
the same position in the array. This is solved either by using an extra
element
in the array or by keeping a counter. I was taught that the "right" way
to do it is
to keep an extra element in the queue, though the counter implementation
may faster to write. It's not difficult to implement in either cases.

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Jan 14 '06 #8
ern wrote:

I need a FIFO queue of size 20, to keep track of a running
average. Once the queue is full with 20 values, I want to take
the sum/20 = AVERAGE. Then when a new value comes in, I want:

(Old Sum - oldest value + newest value)/20 = New Average

Anybody know an efficient way to implement that? Is a queue
even the best way?


After seeing the thread, the following (untested) code may help:

#define SIZE 20

double movingavg(doubl e newvalue)
{
static double sum = 0.0;
static int index = 0;
static double history[SIZE] = 0;
static int full = 0;

sum -= history[index];
sum += (history[index++] = newvalue);
if (index >= SIZE) {
index -= SIZE;
full = 1;
}
if (full) return sum / SIZE;
else return sum / index;
}

The initialization of the static values is crucial. This is not
quite kosher since it assumes all bits 0 represents a double 0.0.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Jan 14 '06 #9
ern wrote:
Logan Shaw wrote:
This doesn't really seem like a C question, since the question would
be the same for just about any programming language. It sounds more
like a data structures and algorithms question. Or maybe a homework
question.
uhhh... it kind of IS a C question since C doesn't support std::queue.


Well, neither does Fortran or Smalltalk -- does that make it a Fortran
question as well? :-)
It's not a homework question... it's actually more of an embedded
systems question, since I'm taking values of floating point current
(analog -> digital). The values are fluctuating, so I need to
implement something to stabilize the output.


Ah, I've run into that problem on Palm OS before, where the digitizer
(for the pen input) is noisy: if I don't filter it out, it makes it
appear to the user that the pen is jumping around the screen slightly,
which is bad.

In my case, I found I don't actually need an array. I just did a
weighted average. If you are just trying to do a running average
of one value, it would look somewhat like this:

float noisy, averaged;

noisy = get_voltage ();
averaged = noisy;

while (1)
{
noisy = get_voltage ();
averaged = (averaged * 7 + noisy) / 8;

display_voltage (averaged);
}

Note that there is one possible problem here: it's not guaranteed for
sure that the average will converge on all possible values because of
round-off error. With floating point (depending on the actual data
you see), this probably won't be a real problem, although it can be with
integer data. (Think of what happens with integers if get_voltage()
returns 10 the first time and then 11 every time after that.) But
even with integers, the round-off problem can be overcome.

- Logan
Jan 14 '06 #10

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

Similar topics

9
2785
by: phil | last post by:
And sorry I got ticked, frustrating week >And I could help more, being fairly experienced with >threading issues and race conditions and such, but >as I tried to indicate in the first place, you've >provided next to no useful (IMHO) information to >let anyone help you more than this This is about 5% of the code. Uses no locks.
4
3572
by: Jeronimo Bertran | last post by:
I have a multithreaded application that manipulates a Queue: protected Queue outputQueue; when I add elements to the queue I use a critical section private void Add(OutputRecord record) { lock(outputQueue) {
5
13247
by: Dan H. | last post by:
Hello, I have implemented a C# priority queue using an ArrayList. The objects being inserted into the priority queue are being sorted by 2 fields, Time (ulong) and Priority (0-100). When I enqueue, I do a binary search on where to put the object and then insert using that index and arraylist.insert(index, obj) The bottom of my arraylist is always my lowest, therefore, dequeueing is very fast and effecient.
7
12370
by: unified | last post by:
Ok, I'm working on a program that is supposed to compare each letter of a string that is put into a stack and a queue. It is supposed to tell whether or not a word is a palindrome or not. (a palindrome is a word that spells the same thing backwards/forewards). I have gotten this much so far: using System; using System.Collections; namespace StackTest {
2
2717
by: Hollywood | last post by:
I have a system in which I have a single thread that places data on a Queue. Then I have one worker thread that waits until data is put on the thread and dequeues the Queue and processes that information. Works just fine. However, I possibly need 1..m worker threads that can act on the same piece of data, i.e. when a dequeue happens on the Queue it can't be removed from the Queue until all threads have used it. I've tried to come up...
6
3736
by: rmunson8 | last post by:
I have a derived class from the Queue base class. I need it to be thread-safe, so I am using the Synchronized method (among other things out of scope of this issue). The code below compiles, but at runtime, the cast of "Queue.Synchronized(new EventQueue())" to an EventQueue object is failing stating invalid cast. Why? public class EventQueue : System.Collections.Queue { ... }
9
2499
by: Brian Henry | last post by:
If i inherite a queue class into my class, and do an override of the enqueue member, how would i then go about actually doing an enqueue of an item? I am a little confused on this one... does over ride just add aditional code ontop of the current class or completely over ride it in vb? I am use to C++ this is the first inherited thing I've done in VB.NET... I'm a little unsure of diffrences, could someone explain this to me some? thanks!
10
2083
by: satan | last post by:
I need the definitions of the method copyQueue, the default constructor, and the copy constructor folr the class LinkedQueueClass. This is what i get so far public abstract class DataElement { public abstract boolean equals(DataElement otherElement); //Method to determine whether two objects contain the //same data. //Postcondition: Returns true if this object contains the
4
2226
by: abcd | last post by:
I have a class such as... id = 0 class Foo: def __init__(self, data): self.id = id id += 1 self.data = data And I am storing them in a Queue.Queue...
4
4598
by: j_depp_99 | last post by:
Thanks to those guys who helped me out yesterday. I have one more problem; my print function for the queue program doesnt work and goes into an endless loop. Also I am unable to calculate the length of my queue. I started getting compilation errors when I included a length function. <code> template<class ItemType> void Queue<ItemType>::MakeEmpty() {
0
9564
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
9387
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10002
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
9938
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8822
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7368
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
6643
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
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
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

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.