Java Distance Calculate calculateDistance(float[] vec1, float[] vec2)

Here you can find the source of calculateDistance(float[] vec1, float[] vec2)

Description

Calculates distance between 2 vectors

License

Open Source License

Parameter

Parameter Description
vec1 a parameter
vec2 a parameter

Declaration

public static float calculateDistance(float[] vec1, float[] vec2) 

Method Source Code

//package com.java2s;
/*/*from   ww w. j ava2 s  . c  om*/
 * Copyright (c) 2008-2013 Maksim Khadkevich and Fondazione Bruno Kessler.
 *
 * This file is part of MART.
 * MART is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2, as published
 * by the Free Software Foundation.
 *
 * MART is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with MART; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

public class Main {
    /**
     * Calculates distance between 2 vectors
     *
     * @param vec1
     * @param vec2
     * @return
     */
    public static float calculateDistance(float[] vec1, float[] vec2) {
        float distance = 0;
        float abs1 = 0;
        float abs2 = 0;
        for (int i = 0; i < vec1.length; i++) {
            distance += vec1[i] * vec2[i];
            abs1 += vec1[i] * vec1[i];
            abs2 += vec2[i] * vec2[i];
        }

        //secure division by zero
        if (abs1 != 0 && abs2 != 0) {
            distance /= (Math.sqrt(abs1) * Math.sqrt(abs2));
        }
        return distance;
    }
}

Related

  1. calculateDistance(double lat1, double lng1, double lat2, double lng2)
  2. calculateDistance(Double lng1, Double lat1, Double lng2, Double lat2)
  3. calculateDistance(Double prevLat, Double prevLon, Double currentLat, Double currentLon)
  4. calculateDistance(double rssi, double txPower)
  5. calculateDistance(final double x1, final double y1, final double x2, final double y2)
  6. calculateDistance(int from, int to)
  7. calculateDistance(int x1, int y1, int z1, int x2, int y2, int z2)
  8. calculateDistance(String firstString, String secondString)
  9. calculateDistanceBetween(double sourceLatitude, double sourceLongitude, double destinationLatitude, double destinationLongitude)