Python Program to Solve Quadratic Equation

0
3018
Program to Solve Quadratic Equation

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

To properly understand this example of a 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

  1. Print hello world! in Python
  2. Addition of Two Numbers in Python
  3. Python Program to find the Square Roots
  4. Python Program to Shuffle Deck of Cards
  5. Python program convert decimal number to binary number using recursion
  6. Python Program to Find Factorial of a Number Using Recursion
  7. Addition of Two Numbers Given by User in Python
  8. Program to find the area of Triangle in Python
  9. Python Program to insert a new node at the beginning of the Circular Linked List.
  10. Python program to create and display a doubly linked list.

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