Java Angle Calculate angleBetween(Point2D.Double vec1, Point2D.Double vec2)

Here you can find the source of angleBetween(Point2D.Double vec1, Point2D.Double vec2)

Description

Computes angle between two vectors, as comptued by the dot product formula

License

Apache License

Parameter

Parameter Description
vec1 first vector
vec2 second vector

Return

angle in the range of 0 to pi.

Declaration

public static double angleBetween(Point2D.Double vec1, Point2D.Double vec2) 

Method Source Code


//package com.java2s;
/*//from  w w  w  .  j  a v  a 2  s.co  m
 * #%L
 * BlaiseMath
 * --
 * Copyright (C) 2009 - 2015 Elisha Peterson
 * --
 * 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.
 * #L%
 */

import java.awt.geom.Point2D;

public class Main {
    /**
     * Computes angle between two vectors, as comptued by the dot product formula
     * @param vec1 first vector
     * @param vec2 second vector
     * @return angle in the range of 0 to pi.
     */
    public static double angleBetween(Point2D.Double vec1, Point2D.Double vec2) {
        return Math.acos(dotProduct(vec1, vec2) / (magnitude(vec1) * magnitude(vec2)));
    }

    /**
     * Computes dot product of two vectors
     * @param v1 first vector
     * @param v2 second vector
     * @return value of dot product
     */
    public static double dotProduct(Point2D.Double v1, Point2D.Double v2) {
        return v1.x * v2.x + v1.y * v2.y;
    }

    /**
     * Computes magnitude of a vector.
     * @param vec the vector
     * @return magnitude
     */
    public static double magnitude(Point2D.Double vec) {
        return vec.distance(0, 0);
    }
}

Related

  1. angle(Point2D from, Point2D to)
  2. angle(Point2D.Double vec)
  3. angle2D(Point p1, Point p2)
  4. angleOf(Point2D a, Point2D b)
  5. anglePI(Point2D top, Point2D corner1, Point2D corner2)
  6. angleToPoint(Rectangle r, double angle)
  7. calculateAngle(double dx, double dy)