quadratic formula in python

To solve a quadratic equation using the quadratic formula in Python, you can follow these steps:

  1. Import the math module, which provides mathematical functions and constants.
  2. Define the coefficients of the quadratic equation: a, b, and c.
  3. Calculate the discriminant (D) using the formula: D = b**2 - 4*a*c.
  4. Check if the discriminant is positive, negative, or zero:
    • If D > 0, there are two real and distinct solutions.
    • If D == 0, there is a single real solution.
    • If D < 0, there are two complex solutions.
  5. Calculate the solutions using the quadratic formula:
    • For D > 0: x1 = (-b + math.sqrt(D)) / (2*a) and x2 = (-b - math.sqrt(D)) / (2*a)
    • For D == 0: x = -b / (2*a)
    • For D < 0: the solutions involve complex numbers.

Here's an example implementation of solving a quadratic equation using the quadratic formula:

main.py
import math

def solve_quadratic_equation(a, b, c):
    D = b**2 - 4*a*c

    if D > 0:
        x1 = (-b + math.sqrt(D)) / (2*a)
        x2 = (-b - math.sqrt(D)) / (2*a)
        return x1, x2
    elif D == 0:
        x = -b / (2*a)
        return x
    else:
        # Complex solutions
        real_part = -b / (2*a)
        imaginary_part = math.sqrt(abs(D)) / (2*a)
        x1 = complex(real_part, imaginary_part)
        x2 = complex(real_part, -imaginary_part)
        return x1, x2

# Example usage
a = 1
b = -6
c = 8
solutions = solve_quadratic_equation(a, b, c)
print("Solutions:", solutions)
601 chars
27 lines

This will output the solutions of the quadratic equation with the given coefficients: (4+0j, 2+0j)

gistlibby LogSnag