A quadratic equation is an equation of the second degree, meaning it contains at least one term that is squared. The standard form is ax² + bx + c = 0
with a, b, and c being constants or numerical coefficients, and x is an unknown variable for example 6x² + 11x - 35 = 0
.
The values of x that make the equation true are called roots of the equation Quadratic equations have 2 roots.
The term b2-4ac
is known as the discriminant of a quadratic equation. The discriminant tells the nature of the roots.
- If the discriminant is greater than 0, the roots are real and different.
- If the discriminant is equal to 0, the roots are real and equal.
- If the discriminant is less than 0, the roots are complex and different.
Problem Definition
Create a Python program to find the roots of a quadratic equation.
Program
import math
a = float(input("Insert coefficient a: "))
b = float(input("Insert coefficient b: "))
c = float(input("Insert coefficient c: "))
discriminant = b**2 - 4 * a * c
if discriminant >= 0:
x_1=(-b+math.sqrt(discriminant))/2*a
x_2=(-b-math.sqrt(discriminant))/2*a
else:
x_1= complex((-b/(2*a)),math.sqrt(-discriminant)/(2*a))
x_2= complex((-b/(2*a)),-math.sqrt(-discriminant)/(2*a))
if discriminant > 0:
print("The function has two distinct real roots: {} and {}".format(x_1,x_2))
elif discriminant == 0:
print("The function has one double root: ", x_1)
else:
print("The function has two complex (conjugate) roots: {} and {}".format(x_1,x_2))
Output
Insert coefficient a: 1
Insert coefficient b: 5
Insert coefficient c: 6
The function has two distinct real roots: -2.0 and -3.0
In the program first, we are importing the built-in math
module to perform complex square root operation later in the program. Then we are taking coefficient inputs from the user.
Next, we are calculating the discriminant using the b2-4ac
formula, based on the result we have a conditional statement to compute the roots for complex conjugates we are using the python complex()
method. Finally, we are printing out the result using string formatting.