Title: Find the tangent lines between a point and a circle in Python
Finding the tangent lines between a point and a circle isn't too hard if you're familiar with the example Determine where two circles intersect in Python.
Consider the figure on the right. R is the radius of the circle. You can easily calculate the distance D between the external point and the circle's center by using the Pythagorean theorem. If the point P is (Px, Py) and the circle's center C is (Cx, Cy), then .
The tangent meets the circle's radius at a 90 degree angle so you can use the Pythagorean theorem again to find .
Believe it or not, you're now done because the tangent points P0 and P1 are the the points of intersection between the original circle and the circle with center P and radius L. Simply use the code from the example Determine where two circles intersect in Python to find those points.
The following code shows how the find_point_circle_tangents method used by the example program finds the tangent points.
def find_point_circle_tangents(center, radius, point):
'''
Return the tangent points for the segments between
a circle and an external point.
'''
# Find the distance squared from the
# external point to the circle's center.
dx = center[0] - point[0]
dy = center[1] - point[1]
dist_squared = dx * dx + dy * dy
if dist_squared < radius * radius:
# The point is inside the circle. Return None.
return None
# Find the distance from the external point
# to the tangent points.
tangent_dist = math.sqrt(dist_squared - radius * radius)
# Find the points of intersection between
# the original circle and the circle with
# center at the point and radius tangent_dist.
intersections = find_circle_circle_intersections(
center, radius, point, tangent_dist)
return intersections
The code calculates the distance D squared. It uses that to calculate L and then calls find_circle_circle_intersections to find the intersections between the two circles. See the previous example for a description of the find_circle_circle_intersections method.
Download the example to see all of the details.
|