示例#1
0
 // return this + that
 public SparseVector plus(SparseVector that) {
   if (this.N != that.N) throw new RuntimeException("Vector lengths disagree");
   SparseVector c = new SparseVector(N);
   for (int i : this.st.keys()) c.put(i, this.get(i)); // c = this
   for (int i : that.st.keys()) c.put(i, that.get(i) + c.get(i)); // c = c + that
   return c;
 }
示例#2
0
  // return the dot product of this vector with that vector
  public double dot(SparseVector that) {
    if (this.N != that.N) throw new RuntimeException("Vector lengths disagree");
    double sum = 0.0;

    // iterate over the vector with the fewest nonzeros
    if (this.st.size() <= that.st.size()) {
      for (int i : this.st.keys()) if (that.st.contains(i)) sum += this.get(i) * that.get(i);
    } else {
      for (int i : that.st.keys()) if (this.st.contains(i)) sum += this.get(i) * that.get(i);
    }
    return sum;
  }