Compute the scalar product of two vectors - Java java.lang

Java examples for java.lang:Math Vector

Description

Compute the scalar product of two vectors

Demo Code

/*/*from  w  w w.j  a va2  s. c  o  m*/
 * Copyright (C) 2014 University of Freiburg.
 *
 * Licensed 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.java2s;

import java.util.HashMap;

public class Main {
    /**
     * Compute the scalar product of two vectors
     * 
     * @param vectorOne
     *          List representing vector one
     * @param vectorTwo
     *          List representing vector two
     * @return Scalar product as double or 0 if the input was invalid.
     */
    public static <T> double computeScalarProduct(
            HashMap<T, Double> vectorOne, HashMap<T, Double> vectorTwo) {

        double scalar = 0;
        for (T key : vectorOne.keySet()) {
            // Check for same key and only compute if a similar entry is found
            // otherwise the product would be zero and therefore no computation
            // is needed
            if (!vectorTwo.containsKey(key))
                continue;

            // Compute scalar if key is found in both vectors
            double valueOne = vectorOne.get(key);
            double valueTwo = vectorTwo.get(key);
            scalar += valueOne * valueTwo;
        }

        return scalar;
    }
}

Related Tutorials