@Override public double dot(Vector x) { if (!x.isDense()) { return super.dot(x); } else { int size = x.size(); if (values.length != size) { throw new CardinalityException(values.length, size); } double sum = 0; for (int n = 0; n < size; n++) { sum += values[n] * x.getQuick(n); } return sum; } }
@Override public double getDistanceSquared(Vector that) { if (size != that.size()) { throw new CardinalityException(size, that.size()); } double thisLength = getLengthSquared(); double thatLength = that.getLengthSquared(); double dot = dot(that); double distanceEstimate = thisLength + thatLength - 2 * dot; if (distanceEstimate > 1.0e-3 * (thisLength + thatLength)) { // The vectors are far enough from each other that the formula is accurate. return Math.max(distanceEstimate, 0); } else { return aggregate(that, Functions.PLUS, Functions.MINUS_SQUARED); } }
@Override public double dot(Vector x) { if (!x.isDense()) { return super.dot(x); } else { int size = x.size(); if (values.length != size) { throw new CardinalityException(values.length, size); } double sum = 0; for (int n = 0; n < size; n++) { sum += values[n] * x.getQuick(n); } return sum; } }
@Override public double getDistanceSquared(Vector that) { if (size != that.size()) { throw new CardinalityException(size, that.size()); } double thisLength = getLengthSquared(); double thatLength = that.getLengthSquared(); double dot = dot(that); double distanceEstimate = thisLength + thatLength - 2 * dot; if (distanceEstimate > 1.0e-3 * (thisLength + thatLength)) { // The vectors are far enough from each other that the formula is accurate. return Math.max(distanceEstimate, 0); } else { return aggregate(that, Functions.PLUS, Functions.MINUS_SQUARED); } }
@Override public double getDistanceSquared(Vector v) { if (size != v.size()) { throw new CardinalityException(size, v.size()); } // if this and v has a cached lengthSquared, dot product is quickest way to compute this. if (lengthSquared >= 0 && v instanceof AbstractVector && ((AbstractVector)v).lengthSquared >= 0) { return lengthSquared + v.getLengthSquared() - 2 * this.dot(v); } Vector randomlyAccessed; Iterator<Element> it; double d = 0.0; if (lengthSquared >= 0.0) { it = v.iterateNonZero(); randomlyAccessed = this; d += lengthSquared; } else { // TODO: could be further optimized, figure out which one is smaller, etc it = iterateNonZero(); randomlyAccessed = v; d += v.getLengthSquared(); } while (it.hasNext()) { Element e = it.next(); double value = e.get(); d += value * (value - 2.0 * randomlyAccessed.getQuick(e.index())); } //assert d > -1.0e-9; // round-off errors should never be too far off! return Math.abs(d); }