Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Conditional Statements

Find roots of a quadratic equation (real/imaginary) - Python Program

Example 1 :

import math a = float(input("a: ")) b = float(input("b: ")) c = float(input("c: ")) d = b**2 - 4*a*c if d > 0: root1 = (-b + math.sqrt(d)) / (2*a) root2 = (-b - math.sqrt(d)) / (2*a) print("Real roots:", root1, root2) elif d == 0: root = -b / (2*a) print("Equal roots:", root) else: real = -b / (2*a) imag = math.sqrt(-d) / (2*a) print("Imaginary roots:", f"{real}+{imag}i", f"{real}-{imag}i")

Output

 
OUTPUT 1 :
a: 5
b: 4
c: 2
Imaginary roots: -0.4+0.4898979485566356i -0.4-0.4898979485566356i

OUTPUT 2 :
a: 1
b: 2
c: 1
Equal roots: -1.0 

OUTPUT 3 :
a: 1
b: -5
c: 2
Real roots: 4.561552812808831 0.4384471871911697

Example 2 : Advanced Program

import cmath def find_quadratic_roots(a, b, c): """ Calculates the roots of a quadratic equation ax^2 + bx + c = 0. Args: a (float): Coefficient of x^2. b (float): Coefficient of x. c (float): Constant term. Returns: tuple: A tuple containing the two roots (real or complex). If 'a' is 0, it indicates an invalid quadratic equation. """ if a == 0: return "Error: 'a' cannot be zero for a quadratic equation." discriminant = (b**2) - 4 * a * c if discriminant >= 0: # Real roots root1 = (-b + cmath.sqrt(discriminant)) / (2 * a) root2 = (-b - cmath.sqrt(discriminant)) / (2 * a) return root1, root2 else: # Complex (imaginary) roots root1 = (-b + cmath.sqrt(discriminant)) / (2 * a) root2 = (-b - cmath.sqrt(discriminant)) / (2 * a) return root1, root2 # Get input from the user try: a = float(input("Enter coefficient 'a': ")) b = float(input("Enter coefficient 'b': ")) c = float(input("Enter coefficient 'c': ")) roots = find_quadratic_roots(a, b, c) if isinstance(roots, str): print(roots) # Print error message if 'a' is 0 elif roots[0] == roots[1]: print(f"The quadratic equation has one real root (repeated): {roots[0]:.4f}") elif isinstance(roots[0], complex): print(f"The quadratic equation has two complex roots: {roots[0]:.4f} and {roots[1]:.4f}") else: print(f"The quadratic equation has two distinct real roots: {roots[0]:.4f} and {roots[1]:.4f}") except ValueError: print("Invalid input. Please enter numeric values for coefficients.")

Output

 
OUTPUT 1 :
Enter coefficient 'a': 1
Enter coefficient 'b': -5
Enter coefficient 'c': 6
The quadratic equation has two complex roots: 3.0000+0.0000j and 2.0000+0.0000j

OUTPUT 2 :
Enter coefficient 'a': 1
Enter coefficient 'b': 2
Enter coefficient 'c': 1
The quadratic equation has one real root (repeated): (-1.0000+0.0000j)

OUTPUT 3 :
Enter coefficient 'a': 1
Enter coefficient 'b': 2
Enter coefficient 'c': 5
The quadratic equation has two complex roots: (-1.0000+2.0000j) and (-1.0000-2.0000j)
 

Explanation

Import cmath:

The cmath module is imported to handle complex number calculations, specifically for finding the square root of negative numbers, which occurs when the roots are imaginary.

find_quadratic_roots Function:

  • Takes three arguments: a, b, and c, representing the coefficients of the quadratic equation ax^2 + bx + c = 0.
  • Handles a = 0: Checks if ais zero. If it is, the equation is not a quadratic equation, and an error message is returned.
  • Calculates Discriminant:The discriminant (b^2 - 4ac) is calculated. This value determines the nature of the roots.
  • Real Roots (Discriminant >= 0):If the discriminant is non-negative, the roots are real. The standard quadratic formula is applied, and sqrt() is used for consistency, although math.sqrt() would also work for non-negative values.
  • Complex Roots (Discriminant < 0):If the discriminant is negative, the roots are complex (imaginary). sqrt() is essential here as it can handle the square root of negative numbers, returning a complex number.
  • Returns a tuple containing the two calculated roots.

User Input and Output:

 

  • Prompts the user to enter the values for coefficients a, b, and c.
  • Calls the find_quadratic_rootsfunction to get the roots.

 

Conditional Output:

  • If the function returns an error string (due to a=0), it prints the error.
  • If the two roots are equal, it indicates a single, repeated real root.
  • If the roots are complex (checked using isinstance(roots[0], complex)), it prints them as complex numbers.
  • Otherwise, it prints the two distinct real roots.
  • Includes a try-exceptblock to handle ValueError if the user enters non-numeric input.