1 | /* |
2 | * Copyright 2010 Savarese Software Research Corporation |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * https://www.savarese.com/software/ApacheLicense-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | |
17 | package com.savarese.spatial; |
18 | |
19 | /** |
20 | * The EuclideanDistance class determines the distance between two |
21 | * points in a Euclidean space. |
22 | */ |
23 | public class EuclideanDistance<Coord extends Number & Comparable<? super Coord>, |
24 | P extends Point<Coord>> |
25 | implements Distance<Coord, P> |
26 | { |
27 | /** |
28 | * Returns the euclidean distance between two points. |
29 | * |
30 | * @param from The first end point. |
31 | * @param to The second end point. |
32 | * @return The distance between from and to. |
33 | */ |
34 | public double distance(P from, P to) { |
35 | return StrictMath.sqrt(distance2(from, to)); |
36 | } |
37 | |
38 | /** |
39 | * Returns the square of the euclidean distance between two points. |
40 | * |
41 | * @param from The first end point. |
42 | * @param to The second end point. |
43 | * @return The square of the euclidean distance between from and to. |
44 | */ |
45 | public double distance2(P from, P to) { |
46 | double d = 0; |
47 | final int imax = from.getDimensions(); |
48 | |
49 | for(int i = 0; i < imax; ++i) { |
50 | double diff = (to.getCoord(i).doubleValue() - |
51 | from.getCoord(i).doubleValue()); |
52 | d+=(diff*diff); |
53 | } |
54 | |
55 | return d; |
56 | } |
57 | } |