Returns the cosine similarity of the two {@code DoubleVector}.
434552
@SuppressWarnings("unchecked")
    public static double cosineSimilarity(DoubleVector a, DoubleVector b) {
        double dotProduct = 0.0;
        double aMagnitude = a.magnitude();
        double bMagnitude = b.magnitude();

        // Check whether both vectors support fast iteration over their non-zero
        // values.  If so, use only the non-zero indices to speed up the
        // computation by avoiding zero multiplications
        if (a instanceof Iterable && b instanceof Iterable) {
            // Check whether we can easily determine how many non-zero values
            // are in each vector.  This value is used to select the iteration
            // order, which affects the number of get(value) calls.
            boolean useA =
                (a.length() < b.length() ||
                 (a instanceof SparseVector && b instanceof SparseVector) &&
                 ((SparseVector)a).getNonZeroIndices().length <
                 ((SparseVector)b).getNonZeroIndices().length);

            // 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++) {
                double aValue = a.get(i);
                double bValue = b.get(i);
                dotProduct += aValue * bValue;
            }
        }
        return (aMagnitude == 0 || bMagnitude == 0)
            ? 0 : dotProduct / (aMagnitude * bMagnitude);
    }

    /**
     * 
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    @SuppressWarnings("unchecked")
    public static double cosineSimilarity(IntegerVector a, IntegerVector b) {
        check(a,b);

        int dotProduct = 0;
        double aMagnitude = a.magnitude();
        double bMagnitude = b.magnitude();

        // Check whether both vectors support fast iteration over their non-zero
        // values.  If so, use only the non-zero indices to speed up the
        // computation by avoiding zero multiplications
        if (a instanceof Iterable && b instanceof Iterable) {
            // Check whether we can easily determine how many non-zero values
            // are in each vector.  This value is used to select the iteration
            // order, which affects the number of get(value) calls.
            boolean useA =
                (a instanceof SparseVector && b instanceof SparseVector)
                && ((SparseVector)a).getNonZeroIndices().length <
                   ((SparseVector)b).getNonZeroIndices().length;

            // 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) {
                IntegerVector t = a;
                a = b;
                b = t;
            }

            for (IntegerEntry e : ((Iterable<IntegerEntry>)b)) {
                int index = e.index();                    
                int aValue = a.get(index);
                int 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 (nzA.length < nzB.length) {
                for (int nz : nzA) {
                    int aValue = a.get(nz);
                    int bValue = b.get(nz);
                    dotProduct += aValue * bValue;
                }
            }
            else {
                for (int nz : nzB) {
                    int aValue = a.get(nz);
                    int bValue = b.get(nz);
                    dotProduct += aValue * bValue;
                }
            }
        }

        // Otherwise, just assume both are dense and compute the full amount
        else {
            for (int i = 0; i < b.length(); i++) {
                int aValue = a.get(i);
                int bValue = b.get(i);
                dotProduct += aValue * bValue;
            }
        }
        return (aMagnitude == 0 || bMagnitude == 0)
            ? 0 : dotProduct / (aMagnitude * bMagnitude);
    }

    /**
     * 
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double cosineSimilarity(Vector a, Vector b) {
        return 
            (a instanceof IntegerVector && b instanceof IntegerVector)
            ? cosineSimilarity((IntegerVector)a, (IntegerVector)b)
            : cosineSimilarity(Vectors.asDouble(a), Vectors.asDouble(b));
    }

    /**
     * Returns the Pearson product-moment correlation coefficient of the two
     * arrays.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double correlation(double[] arr1, double[] arr2) {
        check(arr1, arr2);

        // REMINDER: this could be made more effecient by not looping
        double xSum = 0;
        double ySum = 0;
        for (int i = 0; i < arr1.length; ++i) {
            xSum += arr1[i];
            ySum += arr2[i];
        }
        
        double xMean = xSum / arr1.length;
        double yMean = ySum / arr1.length;
    
        double numerator = 0, xSqSum = 0, ySqSum = 0;
        for (int i = 0; i < arr1.length; ++i) {
            double x = arr1[i] - xMean;
            double y = arr2[i] - yMean;
            numerator += x * y;
            xSqSum += (x * x);
            ySqSum += (y * y);
        }
        if (xSqSum == 0 || ySqSum == 0)
            return 0;

        return numerator / Math.sqrt(xSqSum * ySqSum);
    }

    /**
     * Returns the Pearson product-moment correlation coefficient of the two
     * arrays.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double correlation(int[] arr1, int[] arr2) {
        check(arr1, arr2);

        // REMINDER: this could be made more effecient by not looping
        long xSum = 0;
        long ySum = 0;
        for (int i = 0; i < arr1.length; ++i) {
            xSum += arr1[i];
            ySum += arr2[i];
        }
        
        double xMean = xSum / (double)(arr1.length);
        double yMean = ySum / (double)(arr1.length);
    
        double numerator = 0, xSqSum = 0, ySqSum = 0;
        for (int i = 0; i < arr1.length; ++i) {
            double x = arr1[i] - xMean;
            double y = arr2[i] - yMean;
            numerator += x * y;
            xSqSum += (x * x);
            ySqSum += (y * y);
        }
        return numerator / Math.sqrt(xSqSum * ySqSum);
    }

    /**
     * Returns the Pearson product-moment correlation coefficient of the two
     * {@code Vector}s.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double correlation(DoubleVector arr1, DoubleVector arr2) {
        check(arr1, arr2);

        check(arr1, arr2);

        // REMINDER: this could be made more effecient by not looping
        double xSum = 0;
        double ySum = 0;
        for (int i = 0; i < arr1.length(); ++i) {
            xSum += arr1.get(i);
            ySum += arr2.get(i);
        }
        
        double xMean = xSum / arr1.length();
        double yMean = ySum / arr1.length();
    
        double numerator = 0, xSqSum = 0, ySqSum = 0;
        for (int i = 0; i < arr1.length(); ++i) {
            double x = arr1.get(i) - xMean;
            double y = arr2.get(i) - yMean;
            numerator += x * y;
            xSqSum += (x * x);
            ySqSum += (y * y);
        }
        return numerator / Math.sqrt(xSqSum * ySqSum);
    }

    /**
     * Returns the Pearson product-moment correlation coefficient of the two
     * {@code Vector}s.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double correlation(IntegerVector arr1, DoubleVector arr2) {
        check(arr1, arr2);

        // REMINDER: this could be made more effecient by not looping
        double xSum = 0;
        double ySum = 0;
        for (int i = 0; i < arr1.length(); ++i) {
            xSum += arr1.get(i);
            ySum += arr2.get(i);
        }
        
        double xMean = xSum / arr1.length();
        double yMean = ySum / arr1.length();
    
        double numerator = 0, xSqSum = 0, ySqSum = 0;
        for (int i = 0; i < arr1.length(); ++i) {
            double x = arr1.get(i) - xMean;
            double y = arr2.get(i) - yMean;
            numerator += x * y;
            xSqSum += (x * x);
            ySqSum += (y * y);
        }
        return numerator / Math.sqrt(xSqSum * ySqSum);
    }

    /**
     * Returns the Pearson product-moment correlation coefficient of the two
     * {@code Vector}s.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double correlation(Vector a, Vector b) {
        return correlation(Vectors.asDouble(a), Vectors.asDouble(b));
    }

    /**
     * Returns the euclidian distance between two arrays of {code double}s.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double euclideanDistance(double[] a, double[] b) {
        check(a, b);        
        double sum = 0;
        for (int i = 0; i < a.length; ++i)
            sum += Math.pow((a[i] - b[i]), 2);
        return Math.sqrt(sum);
    }

    /**
     * Returns the euclidian distance between two arrays of {code double}s.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double euclideanDistance(int[] a, int[] b) {
        check(a, b);
        
        long sum = 0;
        for (int i = 0; i < a.length; ++i)
            sum += Math.pow(a[i] - b[i], 2);
        return Math.sqrt(sum);
    }

    /**
     * Returns the euclidian distance between two {@code DoubleVector}s.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double euclideanDistance(DoubleVector a, DoubleVector b) {
        check(a, b);
        
        if (a instanceof SparseVector && b instanceof SparseVector) {
            SparseVector svA = (SparseVector)a;
            SparseVector svB = (SparseVector)b;

            int[] aNonZero = svA.getNonZeroIndices();
            int[] bNonZero = svB.getNonZeroIndices();
            TIntSet union = new TIntHashSet(aNonZero);
            union.addAll(bNonZero);
            
            double sum = 0;
            int[] nzIndices = union.toArray();
            for (int nz : nzIndices) {
                double x = a.get(nz);
                double y = b.get(nz);
                double diff = x - y;
                sum += diff * diff;
            }
            return Math.sqrt(sum);

        } else if (b instanceof SparseVector) {
            // If b is sparse, use a special case where we use the cached
            // magnitude of a and the sparsity of b to avoid most of the
            // computations.
            SparseVector sb = (SparseVector) b;
            int[] bNonZero = sb.getNonZeroIndices();
            double sum = 0;

            // Get the magnitude for a.  This value will often only be computed
            // once for the first vector once since the DenseVector caches the
            // magnitude, thus saving a large amount of computation.
            double aMagnitude = Math.pow(a.magnitude(), 2);

            // Compute the difference between the nonzero values of b and the
            // corresponding values for a.
            for (int index : bNonZero) {
                double value = a.get(index);
                // Decrement a's value at this index from it's magnitude.
                aMagnitude -= Math.pow(value, 2);
                sum += Math.pow(value - b.get(index), 2);
            }

            // Since the rest of b's values are 0, the difference between a and
            // b for these values is simply the magnitude of indices which have
            // not yet been traversed in a.  This corresponds to the modified
            // magnitude that was computed.
            sum += aMagnitude;

            return (sum < 0d) ? 0 : Math.sqrt(sum);
        }

        double sum = 0;
        for (int i = 0; i < a.length(); ++i)
            sum += Math.pow((a.get(i) - b.get(i)), 2);
        return Math.sqrt(sum);
    }

    /**
     * Returns the euclidian distance between two {@code DoubleVector}s.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double euclideanDistance(IntegerVector a, IntegerVector b) {
        check(a, b);
         
        if (a instanceof SparseVector && b instanceof SparseVector) {
            SparseVector svA = (SparseVector)a;
            SparseVector svB = (SparseVector)b;

            int[] aNonZero = svA.getNonZeroIndices();
            int[] bNonZero = svB.getNonZeroIndices();
            HashSet<Integer> sparseIndicesA = new HashSet<Integer>(
                    aNonZero.length);
            double sum = 0;
            for (int nonZero : aNonZero) {
                sum += Math.pow((a.get(nonZero) - b.get(nonZero)), 2);
                sparseIndicesA.add(nonZero);
            }

            for (int nonZero : bNonZero)
                if (!sparseIndicesA.contains(bNonZero))
                    sum += Math.pow(b.get(nonZero), 2);
            return sum;
        }

        double sum = 0;
        for (int i = 0; i < a.length(); ++i)
            sum += Math.pow((a.get(i) - b.get(i)), 2);
        return Math.sqrt(sum);
    }

    /**
     * Returns the euclidian distance between two {@code Vector}s.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double euclideanDistance(Vector a, Vector b) {
        return euclideanDistance(Vectors.asDouble(a), Vectors.asDouble(b));
    }

    /**
     * Returns the euclidian similiarty between two arrays of values.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double euclideanSimilarity(int[] a, int[] b) {
        return 1 / (1 + euclideanDistance(a,b));
    }

    /**
     * Returns the euclidian similiarty between two arrays of values.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double euclideanSimilarity(double[] a, double[] b) {
        return 1 / (1 + euclideanDistance(a,b));
    }

    /**
     * Returns the euclidian similiarty between two arrays of values.
     *
     * @throws IllegalArgumentException when the length of the two vectors are
     *                                   not the same.
     */
    public static double euclideanSimilarity(Vector a, Vector b) {
        return 1 / (1 + euclideanDistance(a,b));
    }

    /**
     * Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
     * index</a> of the two sets of elements.
     */
    public static double jaccardIndex(Set<?> a, Set<?> b) {        
        int intersection = 0;
        for (Object o : a) {
            if (b.contains(o))
                intersection++;
        }

        double union = a.size() + b.size() - intersection;
        return intersection / union;
    }

    /**
     * Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
     * index</a> comparing the similarity both arrays when viewed as sets of
     * samples.
     */
    public static double jaccardIndex(double[] a, double[] b) {        
        Set<Double> intersection = new HashSet<Double>();
        Set<Double> union = new HashSet<Double>();
        for (double d : a) {
            intersection.add(d);
            union.add(d);
        }
        Set<Double> tmp = new HashSet<Double>();
        for (double d : b) {
            tmp.add(d);
            union.add(d);
        }

        intersection.retainAll(tmp);
        return ((double)(intersection.size())) / union.size();
    }

    /**
     * Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
     * index</a> comparing the similarity both arrays when viewed as sets of
     * samples.
     */
    public static double jaccardIndex(int[] a, int[] b) {
        // The BitSets should be faster than a HashMap since it's back by an
        // array and operations are just logical bit operations and require no
        // auto-boxing.  However, if a or b contains large values, then the cost
        // of creating the necessary size for the BitSet may outweigh its
        // performance.  At some point, it would be useful to profile the two
        // methods and their associated worst cases. -jurgens
        BitSet c = new BitSet();
        BitSet d = new BitSet();
        BitSet union = new BitSet();
        for (int i : a) {
            c.set(i);
            union.set(i);
        }
        for (int i : b) {
            d.set(i);
            union.set(i);
        }
        
        // get the intersection
        c.and(d); 
        return ((double)(c.cardinality())) / union.cardinality();
    }
1015821
public IntFloatSortedVector getDiff(IntFloatVector other) {
        IntFloatSortedVector diff = new IntFloatSortedVector(this);
        diff.subtract(other);
        return diff;
    }
1165484
static Vector2d getNearestVector(final Vector2d reference, final List<Vector2d> vectors) {

        if (vectors.isEmpty()) throw new IllegalArgumentException("No vectors provided");

        // to find the closest vector we find use the dot product,
        // for the general case (non-unit vectors) one can use the
        // cosine similarity
        Vector2d closest = vectors.get(0);
        double maxProd = reference.dot(closest);

        for (int i = 1; i < vectors.size(); i++) {
            double newProd = reference.dot(vectors.get(i));
            if (newProd > maxProd) {
                maxProd = newProd;
                closest = vectors.get(i);
            }
        }

        return closest;
    }
1107273
public IMatrix similar(IMatrix U) {
        IMatrix result = new IMatrix(rows, columns);
        similar(U, result);
        return result;
    }
1334992
@Override
  public double distance(NumberVector v1, NumberVector v2) {
    if(v1.getDimensionality() != v2.getDimensionality()) {
      throw new IllegalArgumentException("Different dimensionality of FeatureVectors\n  " + "first argument: " + v1 + "\n  " + "second argument: " + v2);
    }

    double sqrDist = 0;
    for(int d = BitsUtil.nextSetBit(dimensions, 0); d >= 0; d = BitsUtil.nextSetBit(dimensions, d + 1)) {
      final double delta = v1.doubleValue(d) - v2.doubleValue(d);
      sqrDist += delta * delta;
    }
    return FastMath.sqrt(sqrDist);
  }
270718
private Vector3d getReferenceAxisCylic() {
		if (rotationGroup.getPointGroup().equals("C2")) {
			Vector3d vr = new Vector3d(subunits.getOriginalCenters().get(0));
			vr.sub(subunits.getCentroid());
			vr.normalize();
			return vr;
		}

		// get principal axis vector that is perpendicular to the principal
		// rotation vector
		Vector3d vmin = null;
		double dotMin = 1.0;
		for (Vector3d v: principalAxesOfInertia) {
			if (Math.abs(principalRotationVector.dot(v)) < dotMin) {
				dotMin = Math.abs(principalRotationVector.dot(v));
				vmin = new Vector3d(v);
			}
		}
		if (principalRotationVector.dot(vmin) < 0) {
			vmin.negate();
		}

		return vmin;
	}
481233
public static double[] plusEquals(final double[] v1, final double[] v2) {
    assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
    for(int i = 0; i < v1.length; i++) {
      v1[i] += v2[i];
    }
    return v1;
  }
274775
public static double[] plusTimes(final double[] v1, final double[] v2, final double s2) {
    assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
    final double[] result = new double[v1.length];
    for(int i = 0; i < result.length; i++) {
      result[i] = v1[i] + v2[i] * s2;
    }
    return result;
  }
920340
public LongIntSortedVector getDiff(LongIntVector other) {
        LongIntSortedVector diff = new LongIntSortedVector(this);
        diff.subtract(other);
        return diff;
    }
1237207
public IntDoubleSortedVector getDiff(IntDoubleVector other) {
        IntDoubleSortedVector diff = new IntDoubleSortedVector(this);
        diff.subtract(other);
        return diff;
    }
1001819
public double distanceSquared(Vector3dc v) {
    	return distanceSquared(v.x(), v.y(), v.z());
    }
323197
public static boolean shapeEquals(int[] shape1, int[] shape2) {
        if (isColumnVectorShape(shape1) && isColumnVectorShape(shape2)) {
            return Arrays.equals(shape1, shape2);
        }

        if (isRowVectorShape(shape1) && isRowVectorShape(shape2)) {
            int[] shape1Comp = squeeze(shape1);
            int[] shape2Comp = squeeze(shape2);
            return Arrays.equals(shape1Comp, shape2Comp);
        }

        //scalars
        if(shape1.length == 0 || shape2.length == 0) {
            if(shape1.length == 0 && shapeIsScalar(shape2)) {
                return true;
            }

            if(shape2.length == 0 && shapeIsScalar(shape1)) {
                return true;
            }
        }


        shape1 = squeeze(shape1);
        shape2 = squeeze(shape2);

        return scalarEquals(shape1, shape2) || Arrays.equals(shape1, shape2);
    }
1129120
static public double cosine(Angle angle) {
        double result = lock(Math.cos(angle.value));
        return result;
    }
1188618
def is_same_vectors(self, vec_set1, vec_set2):
        
        if (np.absolute(rel_strain(vec_set1[0], vec_set2[0])) >
                self.max_length_tol):
            return False
        elif (np.absolute(rel_strain(vec_set1[1], vec_set2[1])) >
                  self.max_length_tol):
            return False
        elif (np.absolute(rel_angle(vec_set1, vec_set2)) >
                  self.max_angle_tol):
            return False
        else:
            return True
931832
public float distanceSquared(Vector3fc v) {
        return distanceSquared(v.x(), v.y(), v.z());
    }
611847
public static double[] timesPlusTimesEquals(final double[] v1, final double s1, final double[] v2, final double s2) {
    assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
    for(int i = 0; i < v1.length; i++) {
      v1[i] = v1[i] * s1 + v2[i] * s2;
    }
    return v1;
  }
384893
public static double Cosine(double x1, double y1, double x2, double y2) {

        double sumProduct = x1 * x2 + y1 * y2;
        double sumP = Math.pow(Math.abs(x1), 2) + Math.pow(Math.abs(x2), 2);
        double sumQ = Math.pow(Math.abs(y1), 2) + Math.pow(Math.abs(y2), 2);
        sumP = Math.sqrt(sumP);
        sumQ = Math.sqrt(sumQ);

        double result = 1 - (sumProduct / (sumP * sumQ));
        return result;
    }