Implement a smoothing function as a simple moving average of 10 samples. That is
ID: 670139 • Letter: I
Question
Implement a smoothing function as a simple moving average of 10 samples. That is simple moving average (SMA)
where pm is the mth sample. With every additional sample added to the "window", remove oldest sample. In other words consider a constant "window" of 100 sample capacity that slides over the samples and calculates the moving average at each step.
Using a sample of say 100 values (you can use the technique in the python sample to extract these 100 values), run this function and submit both input as well as output.
Bonus points if you can actually plot both the original and the SMA values in a plot and submit the same.
Explanation / Answer
using System;
using Clifton.Collections.Generic;
namespace Clifton.Tools.Data
{
public class SimpleMovingAverage : IMovingAverage
{
CircularList<float> samples;
protected float total;
public float Average
{
get
{
if (samples.Count == 0)
{
throw new ApplicationException("Number of samples is 0.");
}
return total / samples.Count;
}
}
public SimpleMovingAverage(int numSamples)
{
if (numSamples <= 0)
{
throw new ArgumentOutOfRangeException("numSamples can't be negative or 0.");
}
samples = new CircularList<float>(numSamples);
total = 0;
}
public void AddSample(float val)
{
if (samples.Count == samples.Length)
{
total -= samples.Value;
}
samples.Value = val;
total += val;
samples.Next();
}
public void ClearSamples()
{
total = 0;
samples.Clear();
}
public void InitializeSamples(float v)
{
samples.SetAll(v);
total = v * samples.Length;
}
}
}
*******************************program model-2*********************************************
using System;
using System.Collections.Generic;
using System.Linq;
namespace SMA
{
class Program
{
static void Main(string[] args)
{
var nums = Enumerable.Range(1, 5).Select(n => (double)n);
nums = nums.Concat(nums.Reverse());
var sma3 = SMA(3);
var sma5 = SMA(5);
foreach (var n in nums)
{
Console.WriteLine("{0} (sma3) {1,-16} (sma5) {2,-16}", n, sma3(n), sma5(n));
}
}
static Func<double, double> SMA(int p)
{
Queue<double> s = new Queue<double>(p);
return (x) =>
{
if (s.Count >= p)
{
s.Dequeue();
}
s.Enqueue(x);
return s.Average();
};
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.