Python Program to Find the Roots of a Quadratic Equation using sqrt() Function
ADVERTISEMENTS
Python program to find the roots of a quadratic equation using sqrt() function. In this article, you will learn how to find roots of quadratic equation in python language using math.sqrt() function.
What is the Quadratic equation?
ax2 + bx + c = 0
Here a, b, and c are the real numbers & a != 0
Here a, b, and c are the real numbers & a != 0
Source Code
# Python Program to Find the Roots of a Quadratic Equation using sqrt() Function
import math
# to call the math.sqrt() function
p, q, r, d, r1, r2, rp, ip = None, None, None, None, None, None, None, None
# p, q, and r - Value of the real numbers
# d - Value of the discriminant
# r1 - Value of the first root
# r2 - Value of the second root
# rp - Value of the real part
# ip - Value of the image part
print ("-----Enter the these coefficients a, b and c----")
p = float (input ())
q = float (input ())
r = float (input ())
d = q * q - 4 * p * r
# This is the condition for real and different roots
if (d > 0):
r1 = (-q + math.sqrt(d)) / (2 * p)
r2 = (-q - math.sqrt(d)) / (2 * p)
print ("\nThe r1 = ", r1, " & r2 = ", r2)
# This is the condition for real and equal roots
elif d == 0:
r1 = r2 = -q / (2 * p)
print ("\nThe r1 = r2 = ", r1, ";\n")
# if the roots are not real number
else:
rp = -q / (2 * p)
ip = math.sqrt(-d) / (2 * p)
print ("\nThe r1 = ", round(rp, 2), "+", round(ip, 2), "i & r2 = ", round(rp, 2), "-", round(ip, 2), "i")
Output
-----Enter the these coefficients a, b and c----
7.3
6.4
5.5
The r1 = -0.44 + 0.75 i & r2 = -0.44 - 0.75 i