Python Program to Solve Quadratic Equations – 2024

Hey guys, in this blog we will see a Python Program to Solve Quadratic Equations using the cmath library.

Code

# Python Program to Solve Quadratic Equations

# Solve the quadratic equation ax**2 + bx + c = 0

import cmath

a = 1
b = 5
c = 6

# calculate the discriminant
determinant = (b**2) - (4*a*c)
root_of_determinant = cmath.sqrt(determinant)

# let's find two solutions
root1 = (-b-root_of_determinant)/(2*a)
root2 = (-b+root_of_determinant)/(2*a)

print(f'The solution are {root1} and {root2}')

Output

The solution are (-3+0j) and (-2+0j)

The formulae for the roots of a quadratic equation are:

root1 = (-b+D0.5)/2a

root2 = (-b-D0.5)/2a

Here we have used the cmath library to find the square root of our Determinant.

We can also say that the roots are -3 and -2 because the imaginary part is 0 in both roots.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

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