Find the roots of the quadratic equation in Python

In this tutorial, we will see how to Find the roots of the quadratic equation in Python programming? By Bipin Kumar Last updated : January 04, 2024

Problem statement

Write a Python program to input three values, and find the roots of the quadratic equation.

Quadratic Equation

An equation in the form of Ax^2 +Bx +C is a quadratic equation, where the value of the variables A, B, and C are constant and x is an unknown variable which we have to find through the Python program. The value of the variable A won't be equal to zero for the quadratic equation. If the value of A is zero then the equation will be linear.

Here, we are assuming a quadratic equation x^2-7x+12=0 which roots are 4 and -3.

Finding the roots of the quadratic equation

  1. We store the value of variables A, B and C which is given by the user and we will use the mathematical approach to solve this.
  2. Here, we find the value of ((B*B)-4*A*C) and store in a variable d.
    1. If the value of the variable d is negative then the value of x will be imaginary numbers and print the roots of the equation is imaginary.
    2. If the value of the variable is positive then x will be real.
  3. Since the equation is quadratic, so it has two roots which are x1
  4. and x2.
    x1=(-B+((B*B)-4*A*C) **0.5)/2*A
    x2=(-B-((B*B)-4*A*C) **0.5)/2*A
    
  5. When we will find the value of roots of the equation from the above, it may be decimal or integer but we want the answer in an integer that's why we will take math.floor() of the value of the variable x.

Python program to find the roots of the quadratic equation

# importing math module
import math

# Input the values
A, B, C = map(int, input("Input three values: ").split())
d = (B**2) - 4 * A * C

if d >= 0:
    s = (-B + (d) ** 0.5) / (2 * A)
    p = (-B - (d) ** 0.5) / (2 * A)
    print(math.floor(s), math.floor(p))
else:
    print("The roots are imaginary")

Output

The output of the above example is:

RUN 1:
Input three values: 1 -7 12
4 3

RUN 2:
Input three values: 1 5 6
-2 -3

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.