Normalizes a vector, such that its length is 1.0 . - Java java.lang

Java examples for java.lang:Math Vector

Description

Normalizes a vector, such that its length is 1.0 .

Demo Code


//package com.java2s;

import java.awt.geom.Point2D;

public class Main {
    /**/*from ww  w  .  jav a  2  s . c  om*/
     * Normalizes a vector, such that its length is {@code 1.0}.
     * 
     * @param v The vector.
     * @return A vector with the length {@code 1.0}.
     */
    public static Point2D normVec(final Point2D v) {
        return mulVec(v, 1.0 / vecLength(v));
    }

    /**
     * Multiplies a point with a scalar.
     * 
     * @param a The point.
     * @param scalar The scalar.
     * @return the scaled version.
     */
    public static Point2D mulVec(final Point2D a, final double scalar) {
        return new Point2D.Double(a.getX() * scalar, a.getY() * scalar);
    }

    /**
     * Calculates the length of a vector. This operation is relatively expensive.
     * To compare two distances, use {@link #vecLengthSqr(Point2D)}.
     * 
     * @param v The vector.
     * @return The length of the vector.
     */
    public static double vecLength(final Point2D v) {
        return Math.sqrt(vecLengthSqr(v));
    }

    /**
     * Calculates the squared length of a vector. This method is much cheaper than
     * {@link #vecLength(Point2D)}.
     * 
     * @param v The vector.
     * @return The squared length.
     */
    public static double vecLengthSqr(final Point2D v) {
        return dot(v, v);
    }

    /**
     * Calculates the dot product of two vectors.
     * 
     * @param a The first vector.
     * @param b The second vector.
     * @return The dot product.
     */
    public static double dot(final Point2D a, final Point2D b) {
        return a.getX() * b.getX() + a.getY() * b.getY();
    }
}

Related Tutorials