2
* Copyright 2009 Google Inc.
4
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5
* use this file except in compliance with the License. You may obtain a copy of
8
* http://www.apache.org/licenses/LICENSE-2.0
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
* License for the specific language governing permissions and limitations under
17
package org.opensatnav.stats;
20
* This class maintains a buffer of doubles. This buffer is a convenient class
21
* for storing a series of doubles and calculating information about them. This
24
* @author Sandor Dornbush
26
public class DoubleBuffer {
29
* The location that the next write will occur at.
34
* The sliding buffer of doubles.
36
private final double[] buffer;
39
* Have all of the slots in the buffer been filled?
41
private boolean isFull;
44
* Creates a buffer with size elements.
46
* @param size the number of elements in the buffer
47
* @throws IllegalArgumentException if the size is not a positive value
49
public DoubleBuffer(int size) {
51
throw new IllegalArgumentException("The buffer size must be positive.");
53
buffer = new double[size];
58
* Adds a double to the buffer. If the buffer is full the oldest element is
61
* @param d the double to add
63
public void setNext(double d) {
64
if (index == buffer.length) {
69
if (index == buffer.length) {
75
* Are all of the entries in the buffer used?
77
public boolean isFull() {
82
* Resets the buffer to the initial state.
90
* Gets the average of values from the buffer.
92
* @return The average of the buffer
94
public double getAverage() {
95
int numberOfEntries = isFull ? buffer.length : index;
96
if (numberOfEntries == 0) {
101
for (int i = 0; i < numberOfEntries; i++) {
104
return sum / numberOfEntries;
108
* Gets the average and standard deviation of the buffer.
110
* @return An array of two elements - the first is the average, and the second
113
public double[] getAverageAndVariance() {
114
int numberOfEntries = isFull ? buffer.length : index;
115
if (numberOfEntries == 0) {
116
return new double[]{0, 0};
120
double sumSquares = 0;
121
for (int i = 0; i < numberOfEntries; i++) {
123
sumSquares += Math.pow(buffer[i], 2);
126
double average = sum / numberOfEntries;
127
return new double[]{average,
128
sumSquares / numberOfEntries - Math.pow(average, 2)};
132
public String toString() {
133
StringBuffer stringBuffer = new StringBuffer("Full: ");
134
stringBuffer.append(isFull);
135
stringBuffer.append("\n");
136
for (int i = 0; i < buffer.length; i++) {
137
stringBuffer.append((i == index) ? "<<" : "[");
138
stringBuffer.append(buffer[i]);
139
stringBuffer.append((i == index) ? ">> " : "] ");
141
return stringBuffer.toString();