geometry

# # Explanation

Let the center point of a circle $C$, radius $R$、2 points which a line $l$ go through $p_1$, $p_2$.
Let cross points of the line and the circle $a$ and $b$.

## # 1. Calculate cross point $p$ of a perpendicular from $C$ to $l$ and $l$

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 $ab$

$p$ devides $ab$ into 2 equal parts.
$\angle{Cpb}$ is a right angle.
Length of $ap$ and $pb$ is, by Pythegorean theorem,

$ap = pb = \sqrt{R^2 - |\vec{Cp}|^2}$

## # 4. Calculate cross points

$a, b = \vec{p} + \vec{e} \cdot \pm ap$

# # 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);
}


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!

Offer jobs or contact me!