Python | Solve Quadratic Equation If Determinant is Negative

Quadratic equations are defined as ax2 + bx + c = 0 where a, b, c are Real Numbers(or Complex Numbers) and x is a variable.

In High School for solving quadratic equations a formula is taught, which is (-b±√(b²-4ac))/(2a) where different values(a, b, c) are taken from Quadratic equation. Mostly value of b²-4ac is referred to as Determinant of Quadratic Equation. So it can be said that formula for finding roots of a Quadratic Equation is (-b±√(d))/(2a). Do not that for roots to exist determinant value(d) should either be zero or 1. But if Determinant(d) is negative then roots of equation will still exist but roots will be Complex Numbers.

In this article, I’ll discuss about How to solve a Quadratic Equation using Python if in case Determinant of Quadratic Equation is negative(d < 0). Moreover, I’ve already written an article about Solving Quadratic Equation if coefficients are Real Numbers, you can check that article here – Using Python Find Roots of a Quadratic Equation.

# Finding roots of Quadratic Equation using Python

# Import Python's Math and cMath Modules
import math
import cmath

a = float(input("Enter coefficient of x square =>"))
b = float(input("Enter coefficient of x =>"))
c = float(input("Enter constant value in equation =>"))

# Calculating Determinant of Quadratic Equation
d = b**2 - 4*a*c

# Checking if Determinant is positive/zero
if (d >= 0):
	# Calculating Roots of Quadratic Equation
	first_root = (-b + math.sqrt(d))/2*a
	second_root = (-b - math.sqrt(d))/2*a
	print("Roots of Quadratic Equation are =>", first_root,",", second_root)
elif (d <0):
	first_root = (-b + cmath.sqrt(d))/2*a
	second_root = (-b - cmath.sqrt(d))/2*a
	print("Roots of Quadratic Equation are =>", first_root,",", second_root)

Output of Above Code

Enter coefficient of x square =>3
Enter coefficient of x =>4
Enter constant value in equation =>5
Roots of Quadratic Equation are => (-6+9.9498743710662j) , (-6-9.9498743710662j)

The difference in code comes up at lines 21, 22 where if Determinant(d) is less than 0. Then square root would be calculated using Python’s cMath Module function sqrt() rather than equivalent sqrt() function from Math Module.


Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts