Return the length of a vector. - Android java.lang

Android examples for java.lang:Math Vector

Description

Return the length of a vector.

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 MadRobot./*from w  w  w .ja va 2 s .  c  o m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *  Elton Kent - initial API and implementation
 ******************************************************************************/
//package com.java2s;

import android.graphics.PointF;

public class Main {
    public static float length(float ax, float ay) {
        return (float) Math.sqrt(ax * ax + ay * ay);
    }

    public static float length(float ax, float ay, float bx, float by) {
        PointF v = createVector(ax, ay, bx, by);
        return length(v);
    }

    /**
     * Return the length of a vector.
     * 
     * @param v
     *            Vector Point
     * @return Length of vector.
     */
    public static float length(PointF v) {
        return length(v.x, v.y);
    }

    /**
     * Compute distance between two points.
     * 
     * @param p0
     *            starting point
     * @param p1
     *            ending point
     * 
     * @return Distance between points.
     */
    public static float length(PointF p0, PointF p1) {
        PointF v = createVector(p0, p1);
        return length(v);
    }

    public static PointF createVector(float ax, float ay, float bx, float by) {
        PointF point = new PointF();
        point.x = bx - ax;
        point.y = by - ay;
        return point;
    }

    /**
     * Construct the vector specified by two points.
     * 
     * @param lineStart
     *            The coordinate of the line starting point
     * @param lineEnd
     *            The coordinate of the line ending point
     * 
     * @return The Vector point
     */
    public static PointF createVector(PointF lineStart, PointF lineEnd) {
        return createVector(lineStart.x, lineStart.y, lineEnd.x, lineEnd.y);
    }
}

Related Tutorials