Test if four points lay on one line. - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

Test if four points lay on one line.

Demo Code


//package com.java2s;

public class Main {
    /**/*from  ww w  . j  ava2 s. c om*/
     * Test if four points lay on one line.
     */
    public static boolean isStraightLine(double x1, double y1, double x2,
            double y2, double x3, double y3, double x4, double y4,
            double straightLineTolerance) {

        // length of segment
        double len = Math.sqrt((x4 - x1) * (x4 - x1) + (y4 - y1)
                * (y4 - y1));
        if (len == 0.) {
            return true; // avoid endless recursion
        }

        double e = straightLineTolerance * len;

        /* common part of area calculation */
        double q = (x1 - x4) * (y1 + y4);

        /* twice the area between p1, p2, and p4 */
        double f = (x2 - x1) * (y1 + y2) + (x4 - x2) * (y2 + y4) + q;

        /* distance from point p2 to line p0_p1 is area f devided by length of line p0_p1 */
        /* instead of distance compare area */
        if (Math.abs(f) < e) {
            /* same procedure with p3 */
            f = (x3 - x1) * (y1 + y3) + (x4 - x3) * (y3 + y4) + q;
            if (Math.abs(f) < e) {
                return true;
            }
        }
        return false;

    }
}

Related Tutorials