The roots of ax² + bx + c = 0 are x = (-b ± √(b² - 4ac)) / 2a. The value under the square root, d = b² - 4ac, is the discriminant. If d is positive there are two real roots, if d is 0 there is one, and if d is negative the roots are complex numbers.
The program
python
import cmath import math a = float(input("a: ")) b = float(input("b: ")) c = float(input("c: ")) if a == 0: print("a must not be 0, or the equation is not quadratic.") else: d = b * b - 4 * a * c print(f"Discriminant = {d:g}") if d > 0: root1 = (-b + math.sqrt(d)) / (2 * a) root2 = (-b - math.sqrt(d)) / (2 * a) print(f"Two real roots: {root1:g} and {root2:g}") elif d == 0: root = -b / (2 * a) print(f"One real root: {root:g}") else: root1 = (-b + cmath.sqrt(d)) / (2 * a) root2 = (-b - cmath.sqrt(d)) / (2 * a) print(f"Two complex roots: {root1:g} and {root2:g}")
Typed in this example: 1, -5, 6. Press Run to type your own.
output
a: 1 b: -5 c: 6 Discriminant = 1 Two real roots: 3 and 2
How it works
- For x² - 5x + 6 = 0, d = 25 - 24 = 1, so √d = 1 and the roots are (5 + 1) / 2 = 3 and (5 - 1) / 2 = 2. Check: 3² - 5 × 3 + 6 = 0.
math.sqrt()raises aValueErrorfor a negative number.cmath.sqrt()(the c is for complex) returns a complex number instead:cmath.sqrt(-16)is4j.- The program checks
a == 0first, because dividing by2 * awould then raise aZeroDivisionError. 2 * ais in brackets. Without them,/ 2 * awould divide by 2 and then multiply by a.
All three cases
The same steps in a function, tested with one equation of each kind:
python
import cmath import math def solve(a, b, c): d = b * b - 4 * a * c if d > 0: return ((-b + math.sqrt(d)) / (2 * a), (-b - math.sqrt(d)) / (2 * a)) if d == 0: return (-b / (2 * a),) return ((-b + cmath.sqrt(d)) / (2 * a), (-b - cmath.sqrt(d)) / (2 * a)) print(solve(1, -5, 6)) print(solve(1, -4, 4)) print(solve(1, 2, 5))
output
(3.0, 2.0) (2.0,) ((-1+2j), (-1-2j))
Python writes the imaginary unit as j, so -1+2j means -1 + 2i. The roots of x² + 2x + 5 = 0 are -1 + 2i and -1 - 2i.