01: /**********************************************************************
02: Copyright (c) 2007 Erik Bengtson and others. All rights reserved.
03: Licensed under the Apache License, Version 2.0 (the "License");
04: you may not use this file except in compliance with the License.
05: You may obtain a copy of the License at
06:
07: http://www.apache.org/licenses/LICENSE-2.0
08:
09: Unless required by applicable law or agreed to in writing, software
10: distributed under the License is distributed on an "AS IS" BASIS,
11: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: See the License for the specific language governing permissions and
13: limitations under the License.
14:
15:
16: Contributors:
17: ...
18: **********************************************************************/package org.jpox.util;
19:
20: import java.util.LinkedList;
21:
22: /**
23: * Math Utilities.
24: */
25: public class MathUtils {
26: /**
27: * Simple Moving Average
28: */
29: public static class SMA {
30: private LinkedList values = new LinkedList();
31:
32: private int length;
33:
34: private double sum = 0;
35:
36: private double average = 0;
37:
38: /**
39: *
40: * @param length the maximum length
41: */
42: public SMA(int length) {
43: if (length <= 0) {
44: throw new IllegalArgumentException(
45: "length must be greater than zero");
46: }
47: this .length = length;
48: }
49:
50: public double currentAverage() {
51: return average;
52: }
53:
54: /**
55: * Compute the moving average.
56: * Synchronised so that no changes in the underlying data is made during calculation.
57: * @param value The value
58: * @return The average
59: */
60: public synchronized double compute(double value) {
61: if (values.size() == length && length > 0) {
62: sum -= ((Double) values.getFirst()).doubleValue();
63: values.removeFirst();
64: }
65: sum += value;
66: values.addLast(new Double(value));
67: average = sum / values.size();
68: return average;
69: }
70: }
71: }
|