Press ESC to close

How to Find all Roots of a Quadratic Equation in Python

Python is a versatile and most popular programming language. It is easy to learn and always known for its simplicity and readability. This is a simple program written in python to find all the roots of quadratic equation. Python programming language is mostly used for machine learning and automation. It’s widely used in various fields such as web development, data analysis, artificial intelligence, scientific computing, and automation, making it one of the most popular languages in the world today.

Steps to Solve:

  1. Calculate the discriminant D=b2−4acD = b^2 – 4acD=b2−4ac.
  2. Check the discriminant:
    • If D>0D > 0D>0, there are two real roots.
    • If D=0D = 0D=0, there is one real root (repeated root).
    • If D<0D < 0D<0, there are two complex roots.
  3. Compute the roots using the quadratic formula.

Here’s a Python code example to find all roots of a quadratic equation:

import math

def find_roots(a, b, c):
    # Calculate the discriminant
    discriminant = b**2 - 4*a*c
    
    # Condition for real and different roots
    if discriminant > 0:
        root1 = (-b + math.sqrt(discriminant)) / (2*a)
        root2 = (-b - math.sqrt(discriminant)) / (2*a)
        print(f"The roots are real and different: {root1}, {root2}")
        
    # Condition for real and same roots
    elif discriminant == 0:
        root = -b / (2*a)
        print(f"The root is real and repeated: {root}")
        
    # Condition for complex roots
    else:
        real_part = -b / (2*a)
        imaginary_part = math.sqrt(-discriminant) / (2*a)
        root1 = complex(real_part, imaginary_part)
        root2 = complex(real_part, -imaginary_part)
        print(f"The roots are complex: {root1}, {root2}")

# Example usage:
a = 1
b = -7
c = 10
find_roots(a, b, c)

Explanation:

  • Discriminant (D): Determines the nature of the roots.
    • If D>0D > 0D>0: Two distinct real roots.
    • If D=0D = 0D=0: One real root (both roots are the same).
    • If D<0D < 0D<0: Two complex roots.
  • Quadratic Formula: Used to calculate the roots based on the discriminant.

Example:

Given the equation x2−7x+10=0x^2 – 7x + 10 = 0x2−7x+10=0 (i.e., a=1a = 1a=1, b=−7b = -7b=−7, c=10c = 10c=10):

  • Discriminant D=(−7)2−4(1)(10)=49−40=9D = (-7)^2 – 4(1)(10) = 49 – 40 = 9D=(−7)2−4(1)(10)=49−40=9.
  • Since D>0D > 0D>0, the roots are real and different: x=5x = 5x=5 and x=2x = 2x=2.

Output:

The roots are real and different: 5.0, 2.0

This code handles all cases of quadratic equations, providing real or complex roots depending on the discriminant.

Leave a Reply

Your email address will not be published. Required fields are marked *