Python Program - Find Roots of a Quadratic Equation


Advertisements

A standard form of a quadratic quation is:

$$ax^2 + bx + c = 0$$

Where:

$$a, b$$ and $$c$$ are real numbers and $$a \ne 0$$.

Roots of the equation are:

$$\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$

For Example:

The roots of equation $$x^2 + 5x + 4 = 0$$ is

$$\frac{-5 \pm \sqrt{5^2 - 4\times1\times4}}{2\times1}$$ = $$\frac{-5 \pm \sqrt{9}}{2}$$ = $$\frac{-5 \pm 3}{2}$$ = $$-4, -1$$

The roots of the equation will be imaginari if $$D = b^2 - 4ac \lt 0$$. For example - the roots of equation $$x^2 + 4x + 5 = 0$$ will be

$$\frac{-4 \pm \sqrt{4^2 - 4\times1\times5}}{2\times1}$$ = $$\frac{-4 \pm \sqrt{-4}}{2}$$ = $$\frac{-4 \pm 2i}{2}$$ = $$-2 \pm i$$


Example: Calculate roots of a Quadratic equation

In the below example, a function called roots is created which takes $$a$$, $$b$$ and $$c$$ as arguemts to calculate the roots of the equation $$ax^2 + bx + c = 0$$.

import math

def roots(a, b, c):
  D = b*b - 4*a*c
  if D >= 0:
    x1 = (-b + math.sqrt(D))/(2*a)
    x2 = (-b - math.sqrt(D))/(2*a)
    print("Roots of the equation ax^2 + bx + c = 0 are :")
    print(x1,"and",x2)
    print("Where a, b, c are",a,",",b,"and",c,"respectively.")
  else:
    x1 = -b/(2*a)
    x2 = math.sqrt(-D)/(2*a)
    print("Roots of the equation ax^2 + bx + c = 0 are imaginary.")
    print("Real part of root:",x1)
    print("Imaginary part of root:",x2)
    print("Where a, b, c are",a,",",b,"and",c,"respectively.")

roots(1,5,4)
print("\n")
roots(1,4,5)

Output

Roots of the equation ax^2 + bx + c = 0 are :
-1.0 and -4.0
Where a, b, c are 1 , 5 and 4 respectively.

Roots of the equation ax^2 + bx + c = 0 are imaginary.
Real part of root: -2.0
Imaginary part of root: -1.0
Where a, b, c are 1 , 4 and 5 respectively.

Example: Using cmath Module

The above problem also be solved by importing cmath module which can handle the complex number.

import cmath

def roots(a, b, c):
  D = b*b - 4*a*c
  x1 = (-b + cmath.sqrt(D))/(2*a)
  x2 = (-b - cmath.sqrt(D))/(2*a)
  print("Roots of the equation ax^2 + bx + c = 0 are :")
  print(x1,"and",x2)
  print("Where a, b, c are",a,",",b,"and",c,"respectively.")

roots(1,5,4)
print("\n")
roots(1,4,5)

Output

Roots of the equation ax^2 + bx + c = 0 are :
(-1+0j) and (-4+0j)
Where a, b, c are 1 , 5 and 4 respectively.

Roots of the equation ax^2 + bx + c = 0 are :
(-2+1j) and (-2-1j)
Where a, b, c are 1 , 4 and 5 respectively.




Advertisements