Quadratic Equation in Python
Posted by Samath
Last Updated: March 02, 2015
  4151

The roots of a quadratic equation ax2+bx+c are given by the quadratic formula

Write a function quadratic in python which returns the greater of the two roots. However, the root is returned when the discriminant (i.e. b2-4ac) is positive when it is negative print a message that there are no real roots.

Code:

import math

def quadratic(a,b,c):
    discriminant = b**2-4*a*c
    if(discriminant<0):
        print("No real roots")
    else:
        discriminant = math.sqrt(discriminant)
        root1 = (-b+discriminant)/(2.0*a)
        root2 = (-b-discriminant)/(2.0*a)
        if(root1 > root2):
            return root1
        else:
            return root2