Computes the circle formed by three points (x1, y1), (x2, y2) and (x3, y3). - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

Computes the circle formed by three points (x1, y1), (x2, y2) and (x3, y3).

Demo Code

/*//from  w  w w.  j  ava 2s . c o  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 {
    /**
     * Computes the circle formed by three points (x1, y1), (x2, y2) and (x3,
     * y3). If the points are collinear, then false is returned and no further
     * computations are done. If the points are not collinear, then the
     * specified array is used to store the result. The center of the circle is
     * stored in index locations 0 and 1, and the radius squared is stored in
     * index location 2. True is returned if the points are not collinear.
     */
    public static boolean getCircle(double x1, double y1, double x2,
            double y2, double x3, double y3, double[] result) {

        double ax = x2 - x1; // first compute vectors
        double ay = y2 - y1; // a and c
        double cx = x1 - x3;
        double cy = y1 - y3;

        double aPerpDOTc = ax * cy - ay * cx;

        if (aPerpDOTc == 0) {
            return false;
        }

        double bx = x3 - x2;
        double by = y3 - y2;
        double bDOTc = bx * cx + by * cy;

        double qo = bDOTc / aPerpDOTc;
        double sx = x1 + (ax - qo * ay) / 2; // found center of circle
        double sy = y1 + (ay + qo * ax) / 2; // (sx, sy)

        double dx = x1 - sx;
        double dy = y1 - sy;
        double rSquared = dx * dx + dy * dy; // radius of the circle squared

        if (result != null) {
            result[0] = sx;
            result[1] = sy;
            result[2] = rSquared;
        }

        return true;
    }
}

Related Tutorials