Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Created December 12, 2020 12:27
Show Gist options
  • Save steveruizok/d8fa857d4fdd1b0e20d2a7f8b8eb8b64 to your computer and use it in GitHub Desktop.
Save steveruizok/d8fa857d4fdd1b0e20d2a7f8b8eb8b64 to your computer and use it in GitHub Desktop.
Circle from three points.
// This is a very fast implementation.
const det = (
a: number,
b: number,
c: number,
d: number,
e: number,
f: number,
g: number,
h: number,
i: number
) => a * e * i + b * f * g + c * d * h - a * f * h - b * d * i - c * e * g
export function circleFromThreePoints(
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number
) {
var a1 = det(x0, y0, 1, x1, y1, 1, x2, y2, 1)
var a = det(x0, y0, 1, x1, y1, 1, x2, y2, 1)
var b = x0 * x0 + y0 * y0
var c = x1 * x1 + y1 * y1
var d = x2 * x2 + y2 * y2
var cx = -det(b, y0, 1, c, y1, 1, d, y2, 1)
var cy = det(b, x0, 1, c, x1, 1, d, x2, 1)
var cr = -det(b, x0, y0, c, x1, y1, d, x2, y2)
return [
-cx / (2 * a),
-cy / (2 * a),
Math.sqrt(cx * cx + cy * cy - 4 * a * cr) / (2 * Math.abs(a))
]
}
// This implementation is about 50% slower, though maybe easier to understand.
export function circleFromThreePoints(
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number
) {
// Slopes
var a = (y1 - y0) / (x1 - x0)
var b = (y2 - y1) / (x2 - x1)
const cx = (a * b * (y0 - y2) + b * (x0 + x1) - a * (x1 + x2)) / (2 * (b - a))
const cy = (-1 * (cx - (x0 + x1) / 2)) / a + (y0 + y1) / 2
const radius = Math.hypot(cy - y0, cx - x0)
return [cx, cy, radius]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment