How to fit a parabola to 3 points without solving a system of equations
Posted on
If you search for a metod to do this, all the results seem to be essentialy the same thing. Write a system of equations, subtract one from the others, solve the simplified system. There are however alternatives. Divided differences comes up if you search hard enough or ask your favorite LLM, but the method I present doesn't seem to be featured anywhere. It is certainly less computationally expensive than naively solving a system of equations, not that it would really matter ;)
def calculate_quadratic_coefficients_2(points):
x1, y1 = points[0]
x2, y2 = points[1]
x3, y3 = points[2]
# We exploit the fact that polynomials are linear
# in their coefficients to decompose a quadratic
# into two polynomials that are easier to solve.
# Fit a linear function to the endpoints.
# We could use any pair, but it's reasonable to choose
# (x1,y1) and (x3,y3) for better numerical stability
# (assuming x1<x2<x3).
b = (y3-y1) / (x3 - x1)
c = y1 - b*x1
# Reduce y2 by the linear polynomial
y2 = y2 - b*x2 - c
# Because reduction would cause the endpoints to equal 0,
# they're roots of y = a(x-x1)(x-x3). Calculate a
a = y2 / ((x2-x1)*(x2-x3))
# We have a and two roots. This is 3 degrees of freedom
# and is enough to calculate coefficients by rearranging
# Vieta's formulas. We also add back b and c
# from the linear function.
b = -a *(x1+x3) + b
c = a*x1*x3 + c
return a, b, c