Given three points, this method returns true if they are collinear, and false otherwise. - Java java.lang

Java examples for java.lang:Math Function

Description

Given three points, this method returns true if they are collinear, and false otherwise.

Demo Code


//package com.java2s;

public class Main {
    /**//from w  w w. j av a2 s .c o  m
     * Given three points, this method returns true if they are collinear, and false otherwise.
     * @param p0
     * @param p1
     * @param p2
     * @return
     */
    public static boolean arePointsCollinear(double[] p0, double[] p1,
            double[] p2) {

        // coefficients for testing collinearity
        double a, b, c;

        // Define the vectors between pairs of the given points 
        double[] vec1 = { p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2] };
        double[] vec2 = { p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2] };

        a = vec1[0] / vec2[0];
        b = vec1[1] / vec2[1];
        c = vec1[2] / vec2[2];

        // If all coefficients are equal then some scalar exists which scales between the vectors
        // e.g. they are linearly dependent and all 3 points are on the same line
        if (a == b && b == c)
            return true;

        return false;
    }
}

Related Tutorials