li.rudin.rt.api.observable.AveragingObservable Maven / Gradle / Ivy
package li.rudin.rt.api.observable;
import java.util.LinkedList;
public class AveragingObservable extends Observable
{
/**
* Creates a new observable with the default number of samples
*/
public AveragingObservable()
{
this(5);
}
/**
* Creates a new observable with the specified number of samples
* @param samples
*/
public AveragingObservable(int samples)
{
this.samples = samples;
}
private final int samples;
private final LinkedList queue = new LinkedList<>();
private Double min, max, avg;
public Double getMin()
{
return min;
}
public Double getMax()
{
return max;
}
@Override
public void set(Double value)
{
queue.add(value);
if (queue.size() > samples)
//Remove first item
queue.removeFirst();
Double min = null;
Double max = null;
Double sum = 0d;
for (Double d: queue)
{
if (min == null || d < min)
min = d;
if (max == null || d > min)
max = d;
sum += d;
}
this.avg = sum / queue.size();
this.max = max;
this.min = min;
super.set(avg);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy