I want to calculate the intersection points between an ellipse and a line using python.
However how do I do it using only mathematical quadratic equation, when given both end points of the line and the center point and radii of the ellipse?
None of the solutions on stackoverflow describe the solution I’m looking for.
They use either numpy, scipy and other libraries or use trigonometry – none of them use a purely mathematical process.
Comparing the solution in this post for example:
You have the ellipse formula:
(x – center_x)^2 / a^2 + (y – center_y)^2 / b^2 = 1
And the line formula:
y = m*x + c
The solution in linked post describes the quadratic formula derived from it on rearrangement:
A=a2m2+b2
B=2a2m(c-k)-2b2h
C=b2h2+a2(c-k)2-a2b2
I want to solve this equation using only math, solving for x, and afterwards solving for y using the line formula.
However when using above formula, the resulting intersection points are erroneous and do not lie on the ellipse or the line.
This is the code I tried (I excluded the part that visualizes the code because of moderator’s criticism who shut down my previous post):
from math import *
def GetIntersectionPoints(line_point_a, line_point_b, center_x, center_y, rad_x, rad_y):
# use line formula to calculate m and c:
x1, y1, x2, y2 = *line_point_a, *line_point_b
m = (y1 - y2) / (x1 - x2) if not x1 - x2 == 0 else 0
c = y2 - (m * x2)
# Using quadratic equation provided in linked solution:
A = (rad_y ** 2) + ((rad_x ** 2) * (m ** 2))
B = (2 * (rad_x ** 2) * m * (c - center_y)) - 2 * (rad_y ** 2) * center_x
C = (rad_y ** 2) * (center_x ** 2) + (rad_x ** 2) * (c - center_y) * 2 - (rad_x ** 2) * (rad_y ** 2)
# Solving quadratic equation:
xi1 = (-B - sqrt((B ** 2) - (4 * A * C))) / (2 * A)
xi2 = (-B + sqrt((B ** 2) - (4 * A * C))) / (2 * A)
# Solving for y:
yi1 = m * xi1 + c
yi2 = m * xi2 + c
return [[xi1, yi1], [xi2, yi2]]
How do I solve the equation and formula correctly in python without using scipy, numpy etc. (or trigonometry and other solutions described on stackoverflow), in purely mathematical fashion, to retrieve the correct intersection points that lie on the ellipse?