Learn about Python Program to Solve Quadratic Equation using cmath Module in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
Python Program to Solve Quadratic Equation using cmath Module
The cmath module in python makes the work easier with the pre-built functions. In the below program we are using cmath module for the calculations.
Program:
# Python program to find roots of quadratic equation
#importing cmath module
import cmath
# inputs from 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 discriminant
dis = (b**2) - (4*a*c)
# find roots of quadratic equation
root1 = (-b-cmath.sqrt(dis))/(2*a)
root2 = (-b+cmath.sqrt(dis))/(2*a)
# print result
print('The roots are {0} and {1}'.format(root1,root2))
Output:
Enter the value of a: 1 Enter the value of b: 4 Enter the value of c: 5 The roots are (-2-1j) and (-2+1j)
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Program to Find Roots of Quadratic Equation using Function in Python