Skip to content

Instantly share code, notes, and snippets.

@RicoElectrico
Last active April 12, 2025 13:00
Show Gist options
  • Save RicoElectrico/759daf32e3a37c0e2e080a4acffb0b53 to your computer and use it in GitHub Desktop.
Save RicoElectrico/759daf32e3a37c0e2e080a4acffb0b53 to your computer and use it in GitHub Desktop.
A method to find coefficients of a quadratic given 3 points in 6 multiplies and 2 divisions
def calculate_quadratic_coefficients(points):
# Extract x and y values from the points
x1, y1 = points[0]
x2, y2 = points[1]
x3, y3 = points[2]
# Set up the determinant of the matrix
D = (x1**2 * (x2 - x3) +
x2**2 * (x3 - x1) +
x3**2 * (x1 - x2))
if D == 0:
raise ValueError("The points do not form a valid quadratic polynomial (D is zero).")
# Determinants for a, b, c
Da = (y1 * (x2 - x3) +
y2 * (x3 - x1) +
y3 * (x1 - x2))
Db = (x1**2 * (y2 - y3) +
x2**2 * (y3 - y1) +
x3**2 * (y1 - y2))
Dc = (x1**2 * (x2 * y3 - x3 * y2) +
x2**2 * (x3 * y1 - x1 * y3) +
x3**2 * (x1 * y2 - x2 * y1))
# Coefficients
a = Da / D
b = Db / D
c = Dc / D
return a, b, c
def calculate_quadratic_coefficients_2(points):
# Extract x and y values from the points
x1, y1 = points[0]
x2, y2 = points[1]
x3, y3 = points[2]
# Fit a linear polynomial (a=0) to the endpoints
b = (y3-y1) / (x3 - x1)
c = y1 - b*x1
# Reduce y2 by the linear polynomial
y2 = y2 - b*x2 - c
# Because reduction caused endpoints to equal 0, they're roots of a polynomial y2 = a(x2-x1)(x2-x3). Calculate a
a = y2 / ((x2-x1)*(x2-x3))
# Calculate rest of coefficients and add back linear polynomial
b = -a *(x1+x3) + b
c = a*x1*x3 + c
return a, b, c
# Example usage:
points = [(1, 2), (2, 3), (3, 5)] # Replace with your points
try:
a, b, c = calculate_quadratic_coefficients(points)
print(f"Coefficients with Cramer's rule: a = {a}, b = {b}, c = {c}")
a, b, c = calculate_quadratic_coefficients_2(points)
print(f"Coefficients with new method: a = {a}, b = {b}, c = {c}")
except ValueError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment