Python - Solve a Quadratic Equation

The quadratic formula is used when solving a quadraticc which cannot ve factorized.
The Standard form the quadratic equation is

    ax**2 + bx + c = 0,
    where a,b and c are real numbers
    and a ≠ 0 

The solution of this quadratic equation is given by

    (-b ± (b**2 - 4*a*c)**0.5 ) / (2*a) 

In this program, you will learn how to solve the quadratic equation.

Program Code : Solve Quadratic Equation



    import cmath

    a = 1
    b = 6
    c = 5
    
    # Calculate the discriminant
    d = (b**2) - (4*a*c)
    
    # Two solutions
    solution1 = (-b-cmath.sqrt(d))/(2*a)
    solution2 = (-b+cmath.sqrt(d))/(2*a)
    
    print('The solutions are {0} and {1}'.format(solution1, solution2))
            
            

Output


    The solutions are (-5+0j) and (-1+0j)
            

In this program, you have used sqrt function from cmath module to perform complex square root. math library for mathematical calculations.

You can use different values for a, b, and c in the above program and check the output.



The following topics can be useful to understand this program.



Related Tutorials