I need to create a User Defined Aggregate (UDA) function in Derby (specifically, a Variance function), but I'm kinda stuck with the proper way to write it.
So far, I have the "template" for the UDA:
public class Variance<V extends Comparable<V>> implements Aggregator<V,V,Variance<V>> {
private ArrayList<V> _values;
public Variance() {/*Empty constructor*/}
public void init() {_values = new ArrayList<V>(); }
public void accumulate(V v) { _values.add(v); }
public void merge(Variance<V> o) { _values.addAll(o._values); }
public V terminate() {
// Here is my issue!!!
}
}
The issue I'm facing is this: To compute the variance I need to calculate something like this:
V sum, sumSq;
int n = _values.size();
if(n <= 0)
return null;
// Initialize sum and sumSq to "zero"
for(V v : _values) {
sum += v; // Or somehow add v to sum
sumSq += Math.pow(v, 2); // Or somehow add (v^2) to sumSq
}
return (sumSq - n * Math.pow(sum / n, 2)) / n;
... but I don't know how to tell that this is only valid for numeric types (integer, decimal or floating-point values).
I think I'm missing something in my code, but I don't know if there's a way to tell this program that V is numeric, and thus, I can use arithmetic operations on values of type V.
So, the specific questions are:
- Is there a way to perform this operations (addition, substraction, product, power) on the values?
- Should I change the definition of
V(somewhat making it extend a "numeric" class, likeDouble)?