Square distance between a point and a line defined by two other points. - Java java.lang

Java examples for java.lang:Math Geometry Distance

Description

Square distance between a point and a line defined by two other points.

Demo Code


//package com.java2s;
import java.awt.geom.*;

public class Main {
    /**//from w ww .j  av a  2 s  . c  o m
     * Square distance between a point and a line defined by two other points.
     * See http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
     * @param x0 The point not on the line.
     * @param y0 The point not on the line.
     * @param x1 A point on the line.
     * @param y1 A point on the line.
     * @param x2 Another point on the line.
     * @param y2 Another point on the line.
     */
    public static double pointLineDistanceSquare(double x0, double y0,
            double x1, double y1, double x2, double y2) {

        final double x2_x1 = x2 - x1;
        final double y2_y1 = y2 - y1;

        final double d = (x2_x1) * (y1 - y0) - (x1 - x0) * (y2_y1);
        final double denominator = x2_x1 * x2_x1 + y2_y1 * y2_y1;
        return d * d / denominator;
    }

    /**
     * Square distance between a point and a line defined by two other points.
     * See http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
     * @param p0 The point not on the line.
     * @param p1 A point on the line.
     * @param p2 Another point on the line.
     */
    public static double pointLineDistanceSquare(Point2D p0, Point2D p1,
            Point2D p2) {
        return pointLineDistanceSquare(p0.getX(), p0.getY(), p1.getX(),
                p1.getY(), p2.getX(), p2.getY());
    }
}

Related Tutorials