Python Program to find roots of a Quadratic Equation

Updated: May 30


There are two method for finding roots of quadratic equation:

Program: First Method:

import cmath

a = float (input("Enter the value of a : ")) b = float (input("Enter the value of b : ")) c = float (input("Enter the value of c : "))

dis = (b * b) - (4 * a * c)

r1=(-b + cmath.sqrt(dis)) / (2 * a) r2=(-b - cmath.sqrt(dis)) / (2 * a)

print(" The square roots of given equation are {0} and {1}".format(r1,r2))

Output:

Enter the value of a : 1.2

Enter the value of b : 2.5

Enter the value of c : 3.5

The square roots of given equation are (-1.0416666666666667+1.3533651474093098j) and (-1.0416666666666667-1.3533651474093098j)

Finding roots of quadratic equation video by Rajesh Sir:



Second Method:

import math

a = float (input("Enter the value of a : ")) b = float (input("Enter the value of b : ")) c = float (input("Enter the value of c : ")) dis = (b * b) - (4 * a * c) if(dis > 0): r1=(-b + math.sqrt(dis)) / (2 * a) r2=(-b - math.sqrt(dis)) / (2 * a) print("Two Distinct Real Roots are {0} and {1} ".format(r1, r2)) elif(dis == 0): r1 = r2 = -b / (2 * a) print("Two Equal are {0} and {1} ".format(r1, r2)) elif(dis < 0): r1 = r2 = -b / (2 * a) imaginary=math.sqrt(-dis) / (2 * a) print("Two Distinct Complex Roots Exists: r1 = %.2f+%.2f and r2 = %.2f-%.2f" %(r1, imaginary, r2, imaginary))

Output:

Enter the value of a : 1

Enter the value of b : 3

Enter the value of c : 2

Two Distinct Real Roots Exists: r1 = -1.00 and r2 = -2.00




73 views0 comments

Recent Posts

See All

Python program to add one or more element in List

Program: #Append() is used for adding one element in List at the end of list. X=[9,18,27] X.append(36) print(X) output: [9, 18, 27, 36] #Insert () is used for add element at any given position in the

Python program to remove elements of a given list

Program: n=[9,18,27,36,45,54,63] print("List=",n) i=int(input("Enter the position of elements to delete : ")) del n[i] print("List after deletion=",n) del n[:2] print("List after deleting first two el

Python program to create a list of 5 numbers

Python program to create a list of 5 numbers. Numbers entered by User. n=[] for i in range(5): j=int(input("Enter number: ")) n.append(j) print("The List is", n) Output: Enter number: 3 Enter number: