Home » Python » Python programs

Find the root of the quadratic equation in Python

In this tutorial, we will see how to find the root of the quadratic equation in Python programming?
Submitted by Bipin Kumar, on October 09, 2019

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.

Algorithm to solve this problem

  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 root of the quadratic equation

# importing math module
import math

A,B,C=map(int,input().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

1 -7 12
4 3





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.