[Math] Distance between a circle and a line segment

geometry

My math is a little rusty here but I'm trying to come up with a formula which I can then turn into a python program I'm writing.

Given

I have a circle located at $(cx,cy)$ with radius $r$ and I have a line segment between points $p_1= (x_1,y_1)$ and $p_2 =(x_2,y_2)$

What is the distance between the segment and the circle?

Is there a simple formula which can satisfy my condition – or do I need to look at multiple cases, for example the distance from each end point to the circle and then the distance from the closest point on the line segment?

Thanks!

Best Answer

Here is an example Python code that solves the optimization problem suggested by @DeepSea

import casadi as ca
opti = ca.Opti()

# Line segment
t = opti.variable()
line_seg = opti.bounded(0, t, 1)
p0 = (-4.0, 0.5)
p1 = (-2.0, 1.5)
x = (1 - t) * p0 + t * p1

# Circle
y = opti.variable(2)
circ = y[0]**2 + y[1]**2 == 1

# Optimization problem
dist_squared = (x[0] - y[0])**2 + (x[1] - y[1])**2
opti.minimize(dist_squared)
opti.subject_to(line_seg)
opti.subject_to(circ)

# Solve
opti.solver('ipopt')
sol = opti.solve()

# Result
print(f"Distance = {sol.value(ca.sqrt(dist_squared))}")
print(f"Point on line segment: {sol.value(x)}")
print(f"Point on circle: {sol.value(y)}")
Related Question