Python Program to Solve Quadratic Equations

This Python program computes the roots of a quadratic equation when coefficients a, b, and c are given as user input.

Imagine an engineer needs to determine the solutions of a quadratic equation that models the behavior of a physical system.

They can input the coefficients into the program to quickly and accurately calculate the roots of the equation.

import cmath

a = float(input("Enter the coefficient of x^2: "))
b = float(input("Enter the coefficient of x: "))
c = float(input("Enter the constant term: "))

# Calculate the discriminant
d = (b ** 2) - (4 * a * c)

# Calculate the solutions using the quadratic formula
sol1 = (-b - cmath.sqrt(d)) / (2 * a)
sol2 = (-b + cmath.sqrt(d)) / (2 * a)

print(f"The solutions are {sol1} and {sol2}.")

The program prompts the user to input the coefficients a, b, and c of the quadratic equation as floating-point numbers.

It calculates the discriminant of the equation using the formula “d = b^2 – 4ac”.

If the discriminant is positive, the equation has two real roots. If it is zero, the equation has one real root. If it is negative, the equation has two complex roots.

Output:

Enter the coefficient of x^2: 1
Enter the coefficient of x: -5
Enter the constant term: 6
The solutions are (3+0j) and (2+0j).

This example shows the quadratic equation is x^2 – 5x + 6 = 0. The program correctly calculates the two real roots of the equation as 3 and 2 and outputs them to the user.

Leave a Comment