Java Distance Calculate distPointSegmentSquared(double px, double py, double qx, double qy, double rx, double ry)

Here you can find the source of distPointSegmentSquared(double px, double py, double qx, double qy, double rx, double ry)

Description

dist Point Segment Squared

License

Apache License

Declaration

public static double distPointSegmentSquared(double px, double py, double qx, double qy, double rx, double ry) 

Method Source Code

//package com.java2s;
/*//from  w  w w . ja va  2s.  c  om
 * Copyright 2011 Mark McKay
 * 
 * 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.
 */

public class Main {
    public static double distPointSegmentSquared(double px, double py, double qx, double qy, double rx, double ry) {
        double sx = px - qx;
        double sy = py - qy;

        //Multiplying r by this value will create r', 
        // the projection of s onto r
        double rScalar = dot(rx, ry, sx, sy) / dot(sx, sy, sx, sy);
        if (rScalar <= 0) {
            //before first point
            return distSquared(px, py, qx, qy);
        } else if (rScalar >= 1) {
            //After last point
            return distSquared(px, py, qx + rx, qy + ry);
        }

        return dot(sx, sy, sx, sy) - rScalar * rScalar * dot(rx, ry, rx, ry);
    }

    public static double dot(double ax, double ay, double bx, double by) {
        return ax * bx + ay * by;
    }

    public static int dot(int ax, int ay, int bx, int by) {
        return ax * bx + ay * by;
    }

    public static double distSquared(double ax, double ay, double bx, double by) {
        double dx = bx - ax;
        double dy = by - ay;
        return dx * dx + dy * dy;
    }
}

Related

  1. distL1(int[] h1, int[] h2)
  2. distortion(double[] xvalues, double[] yvalues, int[] include)
  3. distpl(double A, double B, double C, double x, double y)
  4. distPointLineSigned(double px, double py, double qx, double qy, double rx, double ry)
  5. distPointLineSquared(double px, double py, double qx, double qy, double rx, double ry)
  6. distribution(int[] values)
  7. distsimFeaturesException()
  8. distSphericalEarth(double lat1, double lon1, double lat2, double lon2)
  9. distSq(double x1, double y1, double x2, double y2)