// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (useA) {
DoubleVector t = a;
a = b;
b = t;
}
for (DoubleEntry e : ((Iterable<DoubleEntry>)b)) {
int index = e.index();
double aValue = a.get(index);
double bValue = e.value();
dotProduct += aValue * bValue;
}
}
// Check whether both vectors are sparse. If so, use only the non-zero
// indices to speed up the computation by avoiding zero multiplications
else if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] nzA = svA.getNonZeroIndices();
int[] nzB = svB.getNonZeroIndices();
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (a.length() < b.length() ||
nzA.length < nzB.length) {
DoubleVector t = a;
a = b;
b = t;
}
for (int nz : nzB) {
double aValue = a.get(nz);
double bValue = b.get(nz);
dotProduct += aValue * bValue;
}
}
// Check if the second vector is sparse. If so, use only the non-zero
// indices of b to speed up the computation by avoiding zero
// multiplications.
else if (b instanceof SparseVector) {
SparseVector svB = (SparseVector)b;
for (int nz : svB.getNonZeroIndices())
dotProduct += b.get(nz) * a.get(nz);
}
// Check if the first vector is sparse. If so, use only the non-zero
// indices of a to speed up the computation by avoiding zero
// multiplications.
else if (a instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
for (int nz : svA.getNonZeroIndices())
dotProduct += b.get(nz) * a.get(nz);
}
// Otherwise, just assume both are dense and compute the full amount
else {
// Swap the vectors such that the b is the shorter vector and a is
// the longer vector, or of equal length. In the case that the two
// vectors of unequal length, this will prevent any calls to out of
// bounds values in the smaller vector.
if (a.length() < b.length()) {
DoubleVector t = a;
a = b;
b = t;
}
for (int i = 0; i < b.length(); i++) {