| 677 | } |
| 678 | |
| 679 | @Override |
| 680 | public double pNormDist(double p, Vec y) |
| 681 | { |
| 682 | if(this.length() != y.length()) |
| 683 | throw new ArithmeticException("Vectors must be of the same length"); |
| 684 | |
| 685 | double norm = 0; |
| 686 | |
| 687 | if (y instanceof SparseVector) |
| 688 | { |
| 689 | int p1 = 0, p2 = 0; |
| 690 | SparseVector b = (SparseVector) y; |
| 691 | |
| 692 | while (p1 < this.used && p2 < b.used) |
| 693 | { |
| 694 | int a1 = indexes[p1], a2 = b.indexes[p2]; |
| 695 | if (a1 == a2) |
| 696 | { |
| 697 | norm += Math.pow(Math.abs(this.values[p1] - b.values[p2]), p); |
| 698 | p1++; |
| 699 | p2++; |
| 700 | } |
| 701 | else if (a1 > a2) |
| 702 | norm += Math.pow(Math.abs(b.values[p2++]), p); |
| 703 | else//a1 < a2, this vec has a value, other does not |
| 704 | norm += Math.pow(Math.abs(this.values[p1++]), p); |
| 705 | } |
| 706 | //One of them is now empty. |
| 707 | //So just sum up the rest of the elements |
| 708 | while(p1 < this.used) |
| 709 | norm += Math.pow(Math.abs(this.values[p1++]), p); |
| 710 | while(p2 < b.used) |
| 711 | norm += Math.pow(Math.abs(b.values[p2++]), p); |
| 712 | } |
| 713 | else |
| 714 | { |
| 715 | int z = 0; |
| 716 | for (int i = 0; i < length(); i++) |
| 717 | { |
| 718 | //Move through until we hit our next non zero element |
| 719 | while (z < used && indexes[z] > i) |
| 720 | norm += Math.pow(Math.abs(-y.get(i++)), p); |
| 721 | |
| 722 | //We made it! (or are at the end). Is our non zero value the same? |
| 723 | if (z < used && indexes[z] == i) |
| 724 | norm += Math.pow(Math.abs(values[z++] - y.get(i)), p); |
| 725 | else//either we used a non zero of this in the loop or we are out of them |
| 726 | norm += Math.pow(Math.abs(-y.get(i)), p); |
| 727 | } |
| 728 | } |
| 729 | return Math.pow(norm, 1.0/p); |
| 730 | } |
| 731 | |
| 732 | @Override |
| 733 | public double pNorm(double p) |