Cross points of a line and a circle
Table of contents
# Explanation
Let the center point of a circle , radius 、2 points which a line go through , .
Let cross points of the line and the circle and .
# 1. Calculate cross point of a perpendicular from to and
Use projection formula
Vector2 project(Vector2 p1, Vector2 p2, Vector2 c) {
Vector2 v = p2 - p1;
return p1 + v * (v.dot(c - p1) / v.norm());
}
# 2. Calculate unit vector \vec
Devide a vector with its length.
Vector2 unitVec(Vector2 v) {
return v / v.length();
}
# 3. Calculate the length of segment
devides into 2 equal parts.
is a right angle.
Length of and is, by Pythegorean theorem,
# 4. Calculate cross points
# Entire Code
double R;
Vector2 C, p1, p2;
Vector2 project(Vector2 p1, Vector2 p2, Vector2 c) {
Vector2 v = p2 - p1;
return p1 + v * (v.dot(c - p1) / v.norm());
}
Vector2 unitVec(Vector2 v) {
return v / v.length();
}
pair<Vector2, Vector2> crossPoints() {
Vector2 p = project(p1, p2, C);
Vector2 e = unitVec(p2 - p1);
double len = sqrt(R*R - (p - C).norm());
Vector2 a = p + e * (-len);
Vector2 b = p + e * len;
if (fabs(a.x) < EPS) a.x = 0.0;
if (fabs(a.y) < EPS) a.y = 0.0;
if (fabs(b.x) < EPS) b.x = 0.0;
if (fabs(b.y) < EPS) b.y = 0.0;
if (a < b) return make_pair(a, b);
return make_pair(b, a);
}
Shun
Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!