Java Euclidean Distance euclideanDistance(double[] l1, double[] l2, boolean weighted)

Here you can find the source of euclideanDistance(double[] l1, double[] l2, boolean weighted)

Description

euclidean Distance

License

Open Source License

Declaration

public static double euclideanDistance(double[] l1, double[] l2, boolean weighted) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static double euclideanDistance(double[] l1, double[] l2, boolean weighted) {
        if (weighted) {
            return weightedEuclideanDistance(l1, l2);
        } else {//from w w w . j  a v a  2  s  .c o  m
            return standardEuclideanDistance(l1, l2);
        }
    }

    /**
     * Computes the euclidean distance between 2 lists with more weight on first elements.
     * 
     * @param l1
     *            list of doubles
     * @param l2
     *            list of doubles
     * @return euclidean distance
     */
    public static double weightedEuclideanDistance(double[] l1, double[] l2) {

        if (l1.length != l2.length) {
            throw new IllegalArgumentException("Both list must have the same number of elements");
        }

        double sum = 0;

        for (int i = 0; i < l1.length; i++) {
            double delta = (l2[i] - l1[i]);
            double weightRatio = (1 / (i + 1));
            sum += delta * delta * weightRatio;
        }

        return Math.sqrt(sum);
    }

    /**
     * Computes the euclidean distance between 2 lists
     * 
     * @param l1
     *            list of doubles
     * @param l2
     *            list of doubles
     * @return euclidean distance
     */
    public static double standardEuclideanDistance(double[] l1, double[] l2) {

        if (l1.length != l2.length) {
            throw new IllegalArgumentException("Both list must have the same number of elements");
        }

        double sum = 0;

        for (int i = 0; i < l1.length; i++) {
            double delta = (l2[i] - l1[i]);
            sum += delta * delta;
        }

        return Math.sqrt(sum);
    }
}

Related

  1. euclideanDistance(double x1, double y1, double x2, double y2)
  2. EuclideanDistance(double xSource, double ySource, double xTarget, double yTarget)
  3. euclideanDistance(double[] a, double[] b)
  4. euclideanDistance(double[] coord1, double[] coord2)
  5. euclideanDistance(double[] data, double[] pattern)
  6. euclideanDistance(double[] p, double[] q)
  7. euclideanDistance(double[] vector)
  8. euclideanDistance(double[] vector1, double[] vector2)
  9. euclideanDistance(float[] points, int p1, int p2, boolean isDisp, double width, double height)