Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
public class forum5020routine {
private static Double[] values= null;
private static int numberOfIterations= 0;
private static int count= 0;
private static int pointer= 0;
/**
* movingAvg: returns the moving average for a predefined number of values
*
* {talendTypes} Double
*
* {Category} User Defined
*
* {param} int("count") count: Number of last values to handle for the arithmetic operation
* {param} Double("value") value: Actual Double value
*
* {example} movingAvg(5, 3.2)
*/
public static Double movingAvg(int count, Double value) {
// initialize count value and array for storing the values
if (forum5020routine.count == 0) {
forum5020routine.count= count;
forum5020routine.values= new Double;
for (int i=0; i < count; i++) {
forum5020routine.values= new Double(0);
}
}
// add the actual value to the array and reset pointer if needed
// the array is used as a circular data container
forum5020routine.values= value;
forum5020routine.pointer++;
if (forum5020routine.pointer >= forum5020routine.count) {
forum5020routine.pointer= 0;
}
// remember the actual iteration. This is only needed to calculate
// the n first values (n < count)
forum5020routine.numberOfIterations++;
// calculate and return value
Double sum= new Double(0.0);
for (Double v: forum5020routine.values) {
sum+=v;
}
if (forum5020routine.numberOfIterations < forum5020routine.count) {
return (sum / forum5020routine.numberOfIterations);
} else {
return (sum / forum5020routine.count);
}
}
}
1|6.74|6.74
2|3.82|5.28
3|1.65|4.07
4|1.71|3.4800000000000004
5|9.3|4.644
6|3.26|3.9480000000000004
7|6.96|4.576
8|1.89|4.6240000000000006
9|2.9|4.862
10|8.27|4.656000000000001