Python Program to Solve Quadratic Equation

534
views
Program to Solve Quadratic Equation
(Last Updated On: November 9, 2018)

In this program, you’ll learn how to computes roots of a quadratic equation when coefficients a, b and c are known.

To properly understand this example of quadratic equation, you should have the knowledge of following Python programming topics:

  1. Python Input, Output and Import
  2. Python Variables and Data Types
  3. Python Operators

The Quadratic Formula uses the “a“, “b“, and “c” from “ax2 bx + c“, where “a“, “b“, and “c” are just numbers; they are the “numerical coefficients” of the quadratic equation they’ve given you to solve.

The Quadratic Formula: For ax2 + bx + c = 0, the values of x which are the solutions of the equation are given by:

quadratic equation roots

For Example: Solve x2 + 3x – 4 = 0

This quadratic happens to factor:

x2 + 3x – 4 = (x + 4)(x – 1) = 0

we already know that the solutions are x = –4 and x = 1.

How would my solution look in the Quadratic Formula?

Using a = 1, b = 3, and c = –4, my solution looks like this:

Quadratic Equation

Then, as expected, the solution is x = –4x = 1.

The standard form of quadratic equations:

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

Program to Solve Quadratic Equation

# import complex math module
import cmath

a = 1
b = 5
c = 6

# To take coefficient input from the users
# a = float(input('Enter a: '))
# b = float(input('Enter b: '))
# c = float(input('Enter c: '))

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

# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

Output

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
Python Program to Solve Quadratic Equation

Here we have imported the cmath module to perform complex square root. First, we calculate the discriminant and then find the two solutions of the quadratic equation.
You can change the value of a, b and c in the above program and test this program.

Related Programs

Ask your questions and clarify your/others doubts on Python quadratic equations by commenting. Python Documentation