Python Program to Find Roots of Quadratic Equation

Python program to find roots of quadratic equation; Through this tutorial, i will show you how to solve or find roots of quadratic equation in python.

Python Program to Solve Quadratic Equation

See the following python program to find roots of quadratic equation; as shown below:

  • Write a Python program to find the roots of an quadratic equation

Write a Python program to find the roots of an quadratic equation

  • Import the python math module in program.
  • Get inputs from the user.
  • Using this formula X = b**2 – 4 * a * c to solve a quadratic equation.
  • Next use conditional statements in the program.
  • Print result.
import math
a = float(input("Insert coefficient a: "))
b = float(input("Insert coefficient b: "))
c = float(input("Insert coefficient c: "))
discriminant = b**2 - 4 * a * c
if discriminant >= 0:
    x_1=(-b+math.sqrt(discriminant))/2*a
    x_2=(-b-math.sqrt(discriminant))/2*a
else:
    x_1= complex((-b/(2*a)),math.sqrt(-discriminant)/(2*a))
    x_2= complex((-b/(2*a)),-math.sqrt(-discriminant)/(2*a))
if discriminant > 0:
    print("The function has two distinct real roots: {} and {}".format(x_1,x_2))
elif discriminant == 0:
    print("The function has one double root: ", x_1)
else:
    print("The function has two complex (conjugate) roots: {}  and {}".format(x_1,x_2))

Output

Insert coefficient a: 1
Insert coefficient b: 5
Insert coefficient c: 6
The function has two distinct real roots: -2.0 and -3.0

Recommended Python Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.