Python – Intersecting Line With Circle

Ever wondered how people can say with 100% security where a circle intersects a line? No? Me too, but still I have decided to try to show how this is done.

We just need a triangle somewhere to be close to the Elder Wand sign from Harry Potter.

With Python it looks like a piece of cake. Just to calculate the points, you need around 5 lines of code:

import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols, Eq, solve

# Define symbols
x, y = symbols('x y')

# Define the equations
line = Eq(x + y, 1)
circle = Eq((x - 2)**2 + (y + 1)**2, 8)

# Solve the system of equations
solutions = solve((line, circle), (x, y))
print(solutions)  # Print to verify

And if you want to plot them beautifully, a bit more:

# Plot the circle
theta = np.linspace(0, 2 * np.pi, 100)
circle_x = 2 + np.sqrt(8) * np.cos(theta)
circle_y = -1 + np.sqrt(8) * np.sin(theta)

# Plot the line
line_x = np.linspace(-2, 5, 100)
line_y = 1 - line_x

plt.figure(figsize=(8, 8))
plt.plot(circle_x, circle_y, label="Circle: $(x-2)^2 + (y+1)^2 = 8$")
plt.plot(line_x, line_y, label="Line: $x + y = 1$")

# Add intersection points
for sol in solutions:
    plt.plot(sol[0], sol[1], 'ro', label=f'Intersection: ({sol[0]}, {sol[1]})')

plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid()
plt.legend()
plt.title("Intersection of a Line and a Circle")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

It is completely other idea, if you need to solve it with pen and paper. Anyway, I have tried to do it in the first 10 minutes of this video:

Intersecting Line With Circle

The pdf of the paper is here – Intersecting_Line_With_Circle.pdf.

Enjoy it!