Python Quadratic Equation Roots Finder
Solve quadratic equations and identify real and complex roots using the discriminant formula in Python.
How it Works
A quadratic equation is in the form ax² + bx + c = 0. Solving it requires the quadratic formula: `x = (-b ± sqrt(b² - 4ac)) / 2a`.
The term `b² - 4ac` is called the discriminant. If positive, there are two distinct real roots. If zero, one real root. If negative, two complex roots.
Python's built-in `cmath` module supports complex numbers, allowing us to find roots even when the discriminant is negative.
Source Code
Robust solver capable of handling real, zero, and complex discriminants.
import cmath
def find_roots(a, b, c):
d = (b**2) - (4*a*c) # discriminant
# Calculate both roots
sol1 = (-b - cmath.sqrt(d)) / (2*a)
sol2 = (-b + cmath.sqrt(d)) / (2*a)
return sol1, sol2
# Test equation: x^2 - 5x + 6 = 0
r1, r2 = find_roots(1, -5, 6)
print("Roots of x^2 - 5x + 6 = 0:")
print(f"Root 1: {r1.real:.1f}")
print(f"Root 2: {r2.real:.1f}")Roots of x^2 - 5x + 6 = 0:
Root 1: 2.0
Root 2: 3.0Real-world Applications
- Physics models and trajectory tracking systems
- Geometric collision detection vectors
- Mathematical solvers
Frequently Asked Questions
Why use `cmath` instead of `math`?
The standard `math` module will raise a ValueError if you try to take the square root of a negative number. The `cmath` (complex math) module automatically handles imaginary roots.
More Examples
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.