Java tutorial
/* * (c) 2005 David B. Bracewell * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.davidbracewell.math.distance; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import java.util.Map; import java.util.Set; /** * @author David B. Bracewell */ public class EuclideanDistance extends DistanceMeasure { @Override public double calculate(Map<?, ? extends Number> m1, Map<?, ? extends Number> m2) { Preconditions.checkNotNull(m1, "Vectors cannot be null"); Preconditions.checkNotNull(m2, "Vectors cannot be null"); double diff = 0d; Set<?> union = Sets.union(m1.keySet(), m2.keySet()); for (Object key : union) { if (!m1.containsKey(key)) { diff += Math.pow(m2.get(key).doubleValue(), 2); } else if (!m2.containsKey(key)) { diff += Math.pow(m1.get(key).doubleValue(), 2); } else { diff += Math.pow(m1.get(key).doubleValue() - m2.get(key).doubleValue(), 2); } } return Math.sqrt(diff); } @Override public double calculate(double[] v1, double[] v2) { Preconditions.checkNotNull(v1, "Vectors cannot be null"); Preconditions.checkNotNull(v2, "Vectors cannot be null"); Preconditions.checkArgument(v1.length == v2.length, "Vector dimension mismatch"); double distance = 0d; for (int i = 0; i < v1.length; i++) { distance += Math.pow(v1[i] - v2[i], 2); } return Math.sqrt(distance); } }//END OF EuclideanDistance