Python Exercises - How to get the roots of the quadratic equation | python exercise #07

Pybeginner
By -
0



Quadratics or quadratic equations can be defined as a polynomial equation of a second degree, which implies that it comprises a minimum of one term that is squared. The general form of the quadratic equation is: 

ax² + bx + c = 0

where x is an unknown variable and a,b,c are numerical coefficients 

Here, a ≠ 0 because if it equals zero then the equation will not remain quadratic anymore and it will become a linear equation, such as: 

bx+c= 0

Suppose, ax² + bx + c = 0 is the quadratic equation, then the formula to find the roots of this equation will be:

x = [-b±√(b2-4ac)]/2

The sign of plus/minus indicates there will be two solutions for x. Learn in detail the quadratic formula here.

 

Now it’s time to calculate the roots.

Tips to follow :

  1. Take the input of the coefficients of a, b and c from the user.

  2. The formula to calculate the roots of the quadratic equation is 

 [-b±√(b ** 2 - (4 * a *c))]/2

  1. First calculate (b ** 2 - (4 * a * c)) and store it in some variable called d for instance.

  2. If d < 0 - It means that the equation has no real roots.

  3. If d = 0 - then calculate (-b / 2a) It means that the equation has double roots.

  4. If d > 0 - then calculate the 2 roots by substituting in the formula. You will get 2 roots.


Program to find the roots of the quadratic equation :


import math  
 
print("This program finds the real solutions to a quadratic\n")
 
a, b, c = eval(input("Please enter the coefficients (a, b, c): "))
 
discrim = b * b - 4 * a * c    
if discrim < 0:
    print("\nThe equation has no real roots!")
elif discrim == 0:
    root = -b / (2 * a)
    print("\nThere is a double root at", root)
else:
    discRoot = math.sqrt(b * b - 4 * a * c)
    root1 = (-b + discRoot) / (2 * a)
    root2 = (-b - discRoot) / (2 * a)
    print("\nThe solutions are:", root1, root2 )



Program to find the roots of the quadratic equation using functions:


 
import math  
 
def roots():
    print("This program finds the real solutions to a quadratic\n")
 
    a, b, c = eval(input("Please enter the coefficients (a, b, c): "))
 
    discrim = b * b - 4 * a * c    
    if discrim < 0:
        print("\nThe equation has no real roots!")
    elif discrim == 0:
        root = -b / (2 * a)
        print("\nThere is a double root at", root)
    else:
        discRoot = math.sqrt(b * b - 4 * a * c)
        root1 = (-b + discRoot) / (2 * a)
        root2 = (-b - discRoot) / (2 * a)
        print("\nThe solutions are:", root1, root2 )
 
roots()



Post a Comment

0Comments

Post a Comment (0)