Java Distance Calculate dist(float x1, float y1, float x2, float y2, float xp, float yp)

Here you can find the source of dist(float x1, float y1, float x2, float y2, float xp, float yp)

Description

Calculate the distance from point (xp, yp) to the line passing through points (x1, y1) and (x2, y2)

License

Apache License

Parameter

Parameter Description
x1 a parameter
y1 a parameter
x2 a parameter
y2 a parameter
xp a parameter
yp a parameter

Return

Distance

Declaration

private static float dist(float x1, float y1, float x2, float y2, float xp, float yp) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from   w w  w. j  ava2 s .  c  o  m
     * Calculate the distance from point (xp, yp) to the line passing through points (x1, y1) and (x2, y2)
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @param xp
     * @param yp
     * @return Distance
     */
    private static float dist(float x1, float y1, float x2, float y2, float xp, float yp) {
        float px = x2 - x1;
        float py = y2 - y1;

        float q = px * px + py * py;

        float u = ((xp - x1) * px + (yp - y1) * py) / q;

        if (u > 1f) {
            u = 1f;
        } else if (u < 0f) {
            u = 0f;
        }

        float x = x1 + u * px;
        float y = y1 + u * py;

        float dx = x - xp;
        float dy = y - yp;

        // Note: If the actual distance does not matter,
        // if you only want to compare what this function
        /// returns to other results of this function, you
        // can just return the squared distance instead
        // (i.e. remove the sqrt) to gain a little performance

        return (float) Math.sqrt(dx * dx + dy * dy);
    }
}

Related

  1. dist(final double x0, final double y0, final double x1, final double y1)
  2. dist(float x1, float y1, float x2, float y2)
  3. dist(float x1, float y1, float x2, float y2)
  4. dist(float x1, float y1, float x2, float y2)
  5. dist(float x1, float y1, float x2, float y2)
  6. dist(float x1, float y1, float z1, float x2, float y2, float z2)
  7. dist(int i, int j, int width)
  8. dist(int p1, int p2)
  9. dist(int x1, int y1, int x2, int y2)