Computes the dot product between two vectors, which is equivalent to Σ this i v i This method should be overloaded for a serious implementation. @param v the other vector @return the dot product of this vector and another
(Vec v)
| 838 | * @return the dot product of this vector and another |
| 839 | */ |
| 840 | public double dot(Vec v) |
| 841 | { |
| 842 | double dot = 0; |
| 843 | if(!this.isSparse() && v.isSparse()) |
| 844 | for(IndexValue iv : v) |
| 845 | dot += get(iv.getIndex())*iv.getValue(); |
| 846 | else if(this.isSparse() && !v.isSparse()) |
| 847 | for(IndexValue iv : this) |
| 848 | dot += iv.getValue()*v.get(iv.getIndex()); |
| 849 | else if(this.isSparse() && v.isSparse()) |
| 850 | { |
| 851 | Iterator<IndexValue> aIter = this.getNonZeroIterator(); |
| 852 | Iterator<IndexValue> bIter = v.getNonZeroIterator(); |
| 853 | |
| 854 | if(this.nnz() == 0 || v.nnz() == 0) |
| 855 | return 0;//All zeros? dot is zer |
| 856 | |
| 857 | //each must have at least one |
| 858 | IndexValue aCur = aIter.next(); |
| 859 | IndexValue bCur = bIter.next(); |
| 860 | |
| 861 | while(aCur != null && bCur != null)//set to null when have none left |
| 862 | { |
| 863 | if(aCur.getIndex() == bCur.getIndex()) |
| 864 | { |
| 865 | dot += aCur.getValue()*bCur.getValue(); |
| 866 | if(aIter.hasNext()) |
| 867 | aCur = aIter.next(); |
| 868 | else |
| 869 | aCur = null; |
| 870 | |
| 871 | if(bIter.hasNext()) |
| 872 | bCur = bIter.next(); |
| 873 | else |
| 874 | bCur = null; |
| 875 | } |
| 876 | else if(aCur.getIndex() < bCur.getIndex()) |
| 877 | { |
| 878 | //Move a over to try and get the indecies equal |
| 879 | if(aIter.hasNext()) |
| 880 | aCur = aIter.next(); |
| 881 | else |
| 882 | aCur = null; |
| 883 | } |
| 884 | else//b is too small, move it over and try to get them lined up |
| 885 | { |
| 886 | if(bIter.hasNext()) |
| 887 | bCur = bIter.next(); |
| 888 | else |
| 889 | bCur = null; |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | } |
| 894 | else |
| 895 | for(int i = 0; i < length(); i++) |
| 896 | dot += get(i)*v.get(i); |
| 897 |