returns the distance between the line formed by (x1, y1), (x2, y2) and the point (x, y). - Java java.lang

Java examples for java.lang:Math Geometry Distance

Description

returns the distance between the line formed by (x1, y1), (x2, y2) and the point (x, y).

Demo Code

/*/*from w  ww  .j a  v  a  2s .co  m*/
 * Copyright (c) JenSoft API
 * This source file is part of JenSoft API, All rights reserved.
 * JENSOFT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
//package com.java2s;

public class Main {
    /**
     * The ptLineDistSq method returns the distance between the line formed by
     * (x1, y1), (x2, y2) and the point (x, y). An array of length >= 3 can be
     * passed in to obtain additional information. If the array is not null,
     * then the closest point on the line to the given point is stored in index
     * locations 0 and 1. The parametric value is stored in index location 2.
     */
    public static double ptLineDistSq(double x1, double y1, double x2,
            double y2, double x, double y, double[] result) {
        double run = x2 - x1;
        double rise = y2 - y1;
        double t = 0.0;
        double f = run * run + rise * rise;

        if (f != 0) {
            t = (run * (x - x1) + rise * (y - y1)) / f;
        }

        double nx = x1 + t * run;
        double ny = y1 + t * rise;

        if (result != null) {
            result[0] = nx;
            result[1] = ny;
            result[2] = t;
        }

        double dx = x - nx;
        double dy = y - ny;
        return dx * dx + dy * dy;
    }

    /**
     * Computes the distance between a line (a, b) and a point (c) in
     * n-dimensions. Arrays a, b, and c must have length greater or equal to n.
     * Array d must have length greater than n. The location of the closest
     * point on the line is stored in d. The parametric value is stored at index
     * location n in d.
     */
    public static double ptLineDistSq(double[] a, double[] b, double[] c,
            double[] d, int n) {
        for (int i = 0; i < n; i++) {
            d[i] = b[i] - a[i];
        }

        double f = 0;
        for (int i = 0; i < n; i++) {
            f = f + d[i] * d[i];
        }

        double t = 0.0;

        if (f != 0) {
            double g = 0;
            for (int i = 0; i < n; i++) {
                g = g + d[i] * (c[i] - a[i]);
            }

            t = g / f;
        }

        for (int i = 0; i < n; i++) {
            d[i] = a[i] + t * d[i];
        }

        d[n] = t;

        double distSq = 0;
        for (int i = 0; i < n; i++) {
            double h = c[i] - d[i];
            distSq = distSq + h * h;
        }

        return distSq;
    }
}

Related Tutorials