Google News
logo
Python Program to Solve Quadratic Equation
Here's a Python program to solve a quadratic equation :
Program :
import cmath

a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient 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 are {0} and {1}".format(sol1, sol2))
Output :
Enter coefficient a: 3
Enter coefficient b: 4
Enter coefficient c: 6
The solutions are (-0.6666666666666666-1.247219128924647j) and (-0.6666666666666666+1.247219128924647j)
In this program, we first take input from the user for the coefficients of the quadratic equation. We then calculate the discriminant using the formula `(b**2) - (4*a*c)`.

If the discriminant is positive, we have two real solutions which we calculate using the formula `(-b ± sqrt(d)) / (2*a)`, where `sqrt` is the square root function provided by the `cmath` module.

If the discriminant is zero, we have one real solution which is calculated using the formula `-b / (2*a)`.

If the discriminant is negative, we have two complex solutions which are calculated using the same formula as above, but with `cmath.sqrt` instead of `sqrt`.