Python Program to Solve Quadratic Equation

Posted in

Python Program to Solve Quadratic Equation
vinaykhatri

Vinay Khatri
Last updated on October 6, 2024

    In this article, we have provided a python source code that is capable of finding the roots for a quadratic equation if the user provides the program with coefficient values of x 2 , x and constant.

    Prerequisite topics to create this program

    • Python Input, Output
    • Python Data types
    • Python Operators
    • python modules

    Steps

    • ask the user to enter the coefficient values of a, b and c real numbers.
    • calculate the discriminant value by suing the formula d = (b**2) - (4*a*c)
    • At last, using the quadratic formula, we will calculate the two possible roots.
    • A quadratic equation could have imaginary root values so for that here we will use the cmath module to perform the sqrt() function.

    General Quadratic Equation

    ax2 + bx + c = 0, where a, b and c are real numbers and a ? 0

    Python Program to Solve Quadratic Equation Code

    import cmath
    
    a = float(input("Enter the coefficient of x sq: "))
    b = float(input("Enter the coefficient of x: "))
    c = float(input("Enter the constant of c sq: " ))
    
    d = (b**2) - (4*a*c)    # calculate the discriminant
    
    # find two root values
    root_1 = (-b-cmath.sqrt(d))/(2*a)
    root_2 = (-b+cmath.sqrt(d))/(2*a)
    
    print('The two possible roots are {0} and {1}'.format(root_1,root_2))

    Input

    Enter the coefficient of x sq: 5
    Enter the coefficient of x: 6
    Enter the constant of c sq: 1

    Output

    The two possible roots are (-1+0j) and (-0.2+0j)

    Behind the Code

    Here the cmath.sqrt() method is used to find the square root of the discriminant value d. For some equation the d could be negative and when it happen the cmath.sqrt() function calculate the square root of the value in complex number.

    People are also reading:

    Leave a Comment on this Post

    0 Comments