Mathematical Programs · Python example
Use the quadratic formula and math.sqrt to find real roots.
The quadratic formula finds the roots of ax² + bx + c = 0. The discriminant decides how many real solutions exist.
import math
a, b, c = 1, -3, 2
discriminant = b ** 2 - 4 * a * c
if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
print(f"Two real roots: {root1:.1f} and {root2:.1f}")
elif discriminant == 0:
root = -b / (2 * a)
print(f"One real root: {root:.1f}")
else:
print("No real roots")