Java Cosine Similarity cosDistance(float[] v1, float[] v2)

Here you can find the source of cosDistance(float[] v1, float[] v2)

Description

Calculate cosine distance of two vectors

License

Open Source License

Parameter

Parameter Description

Return

cosine distance

Declaration

public static float cosDistance(float[] v1, float[] v2) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*ww w.j  a  v a2 s  . com*/
     * Calculate cosine distance of two vectors
     *
     * @param v1, vector 1
     * @param v2, vector 2
     * @return cosine distance
     */
    public static float cosDistance(float[] v1, float[] v2) {
        assert v1.length == v2.length;
        float dotProduct = dotProduct(v1, v2);
        float sumNorm = vectorNorm(v1) * vectorNorm(v2);
        return dotProduct / sumNorm;
    }

    /**
     * Calculate the dot-product result of two vectors.
     *
     * @param v1, vector 1
     * @param v2, vector 2
     * @return dot product
     */

    public static float dotProduct(float[] v1, float[] v2) {
        assert v1.length == v2.length;
        float result = 0;
        for (int i = 0; i < v1.length; i++) {
            result += v1[i] * v2[i];
        }
        return result;
    }

    /**
     * Calculate the norm of a vector
     *
     * @param v, a float vector
     * @return norm
     */
    public static float vectorNorm(float[] v) {
        float result = 0;
        for (float aV : v) {
            result += aV * aV;
        }
        result = (float) Math.sqrt(result);
        return result;
    }
}

Related

  1. cosDegrees(double angleInDegrees)
  2. cosine_similarity(double[] vec1, double[] vec2)
  3. cosineLawGetDegree(double a, double b, double c)
  4. cosineSim(double[] a, double[] b)
  5. cosineSimilarity(double[] vector1, double[] vector2)