本文展示如何使用 Java 實作平面幾何運算,包含點、線段類別,以及計算兩直線交點、三角形外心(圓心)與內心的完整演算法。
class Point {
double x, y;
public Point() { this.x = 0; this.y = 0; }
}
class Line {
Point a, b;
public Line() {
this.a = new Point();
this.b = new Point();
}
}
使用向量參數式方程求解,避免斜率不存在的問題:
Point intersection(Line u, Line v) {
Point res = u.a;
double t = ((u.a.x - v.a.x) * (v.b.y - v.a.y) - (u.a.y - v.a.y) * (v.b.x - v.a.x))
/ ((u.a.x - u.b.x) * (v.b.y - v.a.y) - (u.a.y - u.b.y) * (v.b.x - v.a.x));
res.x += (u.b.x - u.a.x) * t;
res.y += (u.b.y - u.a.y) * t;
return res;
}
外心是三邊中垂線交點。利用向量性質:
(GA + GB) · AB = 0 等同於 G 在 AB 中垂線上。
Point circumcenter(Point a, Point b, Point c) {
Line u = new Line(), v = new Line();
// AB 的中點
u.a.x = (a.x + b.x) / 2;
u.a.y = (a.y + b.y) / 2;
// 中垂線方向向量:垂直於 AB
u.b.x = u.a.x + (u.a.y - a.y);
u.b.y = u.a.y - (u.a.x - a.x);
// AC 的中點
v.a.x = (a.x + c.x) / 2;
v.a.y = (a.y + c.y) / 2;
v.b.x = v.a.x + (v.a.y - a.y);
v.b.y = v.a.y - (v.a.x - a.x);
return intersection(u, v); // 兩中垂線交點即外心
}
內心到三邊距離相等(半徑 r)。座標公式為邊長加權平均:
// 邊長
double a = distance(b, c); // BC
double b = distance(a, c); // CA
double c = distance(a, b); // AB
// 內心座標
double x = (a.x * a + b.x * b + c.x * c) / (a + b + c);
double y = (a.y * a + b.y * b + c.y * c) / (a + b + c);
推導原理:內心是角平分線交點,向量滿足 a·MA + b·MB + c·MC = 0,解得上述公式。
半徑可由海倫公式求面積 S,再用 r = 2S / (a+b+c) 計算。
設三角形 ABC,內心 O,邊長 a=BC, b=CA, c=AB。
證明 a·OA + b·OB + c·OC = 0:
利用角平分線定理與向量分解,可證明向量和為零向量,確立內心座標公式正確性。
double 保持精度GeometryUtils 供專案複用