Python Program to Solve Quadratic Equation Ad Sponsored

ⓘ Sponsored by

A quadratic equation is an algebraic equation of the second degree in x1. That means it has a term with x² as well as terms with x and a constant. A quadratic equation can be written in the standard form as ax² + bx + c = 0, where a, b and c are known numbers and a ≠ 0231. For example, 2x² - 5x + 3 = 0 is a quadratic equation. A quadratic equation can have two solutions, one solution or no solution depending on its discriminant1. The discriminant is b² - 4ac and it tells you how many roots (or zeros) the equation has4. To find the solutions of a quadratic equation, you can use different methods such as factoring, completing the square or using the quadratic formula154. The quadratic formula is x = (-b ± √(b² - 4ac))/(2a) and it works for any quadratic equation

Python Code :

Standard form of a quadratic equation is:

ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0

The solutions of this quadratic equation is given by:

(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)

The below Python program to solve quadratic equations:

import math

# Get input coefficients a, b, c from user
a = float(input("Enter the coefficient a: "))
b = float(input("Enter the coefficient b: "))
c = float(input("Enter the coefficient c: "))

# Calculate discriminant
discriminant = b**2 - 4*a*c

# Check if discriminant is positive, negative or zero
if discriminant > 0:
    root1 = (-b + math.sqrt(discriminant)) / (2*a)
    root2 = (-b - math.sqrt(discriminant)) / (2*a)
    print("The roots are real and distinct.")
    print("Root 1 is:", root1)
    print("Root 2 is:", root2)
elif discriminant == 0:
    root = -b / (2*a)
    print("The roots are real and equal.")
    print("The root is:", root)
    real_part = -b / (2*a)
    imag_part = math.sqrt(-discriminant) / (2*a)
    print("The roots are complex conjugates.")
    print("Root 1 is:", real_part, "+", imag_part, "i")
    print("Root 2 is:", real_part, "-", imag_part, "i")

In this program, the user is prompted to enter the three coefficients of the quadratic equation, a, b and c.

For a = 10 , b = 15 , c = 16, the output is :

The roots are complex conjugates.
Root 1 is: -0.75 + 1.0185774393731681 i
Root 2 is: -0.75 - 1.0185774393731681 i

The discriminant is calculated using the formula b^2 - 4ac.

Then, based on the value of the discriminant, the program determines the nature of the roots of the quadratic equation and prints them out.

Note that this program uses the math module to compute the square root and the imaginary part of the root Ad Sponsored

ⓘ Sponsored by