多次元ベクトル間のユークリッド距離を計算する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.util.*; public class Main { public static void main(String[] args) throws Exception { double[] P1 = {5, -4}; double[] Q1 = {-7, 10}; double d1 = calcEuclideanDistance(P1, Q1); pln(d1); double[] P2 = {5, -4, 13}; double[] Q2 = {-7, 10, -13}; double d2 = calcEuclideanDistance(P2, Q2); pln(d2); } public static double calcEuclideanDistance(double[] p, double[] q) throws Exception { if(p.length != q.length){ throw new Exception( "引数のベクトルの次元が異なる。" + "p.length:" + p.length + ", " + "q.length:" + q.length ); } double rightSquaredValue = 0; for(int i=0; i<p.length; i++){ rightSquaredValue += Math.pow(p[i] - q[i], 2); } double euclideanDistance = Math.sqrt(rightSquaredValue); return euclideanDistance; } public static void pln() { System.out.println(); } public static void pln(Object o) { System.out.println(o); } } |
1 2 |
18.439088914585774 31.874754901018456 |