Example
Input
8
-4
-2
Output
0.8090169943749475 -0.30901699437494745
Required to know
Use of Variables, Use of different operators like assignment or arithmetic operators, Use of functions like print(), and input(), Use of If-else, and Use of Data types.
Quadratic Equation
The simple equation for the quadratic equation in terms of elementary algebra is ax^2+bx+c = 0.
Now the quadratic equation can have one or two distinct, real and complex roots. It also depends upon the discriminant which can be found by: -
delta = b^2 = 4ac.
Based on the discriminant formula we get three conditions to find the distinct, real and complex roots.
If the discriminant is positive: - we get two real distinct roots.
If the discriminant is zero: - one real root.
If the discriminant is negative: - two distinct complex roots.
Steps
Import the math module.
We need to get the coefficients/values of the quadratic equation from the user.
Calculate the discriminant by using the formula b^2 -4ac.
Now we have to check if the discriminant is positive, zero, or negative. So the condition needs to get divided in this manner,
If the discriminant is positive, there are two distinct real roots.
If the discriminant is zero, there is one repeated real root.
If the discriminant is negative, there are two distinct complex roots. Print the roots of the equation
# Import the math module
import math
# Get the coefficients of the quadratic equation from the 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 the discriminant
discriminant = b**2 - 4 * a * c
# Check if the discriminant is positive, zero, or negative
if discriminant > 0:
# There are two distinct real roots
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
print("Two distinct and real roots exists:", root1, root2)
elif discriminant == 0:
# There is one repeated real root
root1 = root2 = -b / (2 * a)
print("Two equal and real roots exists:", root1)
else:
# There are two distinct complex roots
root1 = -b / (2 * a)
imaginary = math.sqrt(-discriminant) / (2 * a)
print("Two distinct complex roots exists:", root1 + imaginary, root1 - imaginary)