In mathematics, a quadratic equation is a polynomial equation of the second degree. It is of the form ax^2 + bx + c = 0, where a, b, and c are constants and x is the unknown variable. The roots of a quadratic equation are the values of x that satisfy the equation. In this tutorial, we will learn how to write a Python program to find the roots of a quadratic equation.
To find the roots of a quadratic equation, we can use the quadratic formula, which is given as:
x = (-b ± √(b^2 – 4ac)) / 2a
where a, b, and c are the coefficients of the quadratic equation. We can use this formula to find the roots of the equation.
Let’s write a Python program to find the roots of a quadratic equation:
import cmath
# take input from the user
a = float(input("Enter the value of a: "))
b = float(input("Enter the value of b: "))
c = float(input("Enter the value of c: "))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b - cmath.sqrt(d)) / (2*a)
sol2 = (-b + cmath.sqrt(d)) / (2*a)
# print the solutions
print("The solutions are {0} and {1}".format(sol1,sol2))
In this program, we have imported the cmath module, which provides complex number support in Python. We have taken input from the user for the coefficients of the quadratic equation. Then, we have calculated the discriminant using the formula (b^2 – 4ac). Depending on the value of the discriminant, we can determine the number of roots of the equation.
If the discriminant is positive, then the equation has two real roots. If the discriminant is zero, then the equation has one real root. If the discriminant is negative, then the equation has two complex roots.
We have used the cmath module to find the two solutions of the quadratic equation. Finally, we have printed the solutions.
Let’s run the program with the following input:
Enter the value of a: 1
Enter the value of b: 5
Enter the value of c: 6
The program will output the following:
The solutions are (-3+0j) and (-2+0j)
These are the two roots of the quadratic equation x^2 + 5x + 6 = 0. The roots are -3 and -2.
Follow us on Twitter: Hacktube5
Follow us on Youtube: Hacktube5