Python Program - Find Roots of a Quadratic Equation
A standard form of a quadratic equation is:
ax2 + bx + c = 0
Where:
a, b and c are real numbers and a ≠ 0.
Roots of the equation are:
For Example:
The roots of equation x2 + 5x + 4 = 0 is
The roots of the equation will be imaginary if D = b2 - 4ac < 0. For example - the roots of equation x2 + 4x + 5 = 0 will be
Method 1: Calculate roots of a Quadratic equation
In the example below, a function called roots is created which takes a, b and c as arguments to calculate the roots of the equation ax2 + 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 are:",x1,",",x2) else: x1 = -b/(2*a) x2 = math.sqrt(-D)/(2*a) print("Roots are:",x1,"±",x2,"i") print("Equation is x*x+5x+4=0") roots(1,5,4) print("\nEquation is x*x+4x+5=0") roots(1,4,5)
The above code will give the following output:
Equation is x*x+5x+4=0 Roots are: -1.0 , -4.0 Equation is x*x+4x+5=0 Roots are: -2.0 ± 1.0 i
Method 2: 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 are:",x1,"and",x2) print("Equation is x*x+5x+4=0") roots(1,5,4) print("\nEquation is x*x+4x+5=0") roots(1,4,5)
The above code will give the following output:
Equation is x*x+5x+4=0 Roots are: (-1+0j) and (-4+0j) Equation is x*x+4x+5=0 Roots are: (-2+1j) and (-2-1j)
Recommended Pages
- Python Program - To Check Prime Number
- Python Program - Bubble Sort
- Python Program - Selection Sort
- Python Program - Maximum Subarray Sum
- Python Program - Reverse digits of a given Integer
- Python - Swap two numbers
- Python Program - Fibonacci Sequence
- Python Program - Insertion Sort
- Python Program - Find Factorial of a Number
- Python Program - Find HCF of Two Numbers
- Python Program - Merge Sort
- Python Program - Shell Sort
- Stack in Python
- Queue in Python
- Python Program - Find LCM of Two Numbers
- Python Program - To Check Whether a Number is Palindrome or Not
- Python Program - To Check Whether a String is Palindrome or Not
- Python Program - Heap Sort
- Python Program - Quick Sort
- Python - Swap Two Numbers without using Temporary Variable