Search code examples
pythonpython-3.xmathsquare-root

Roots of a quadratic function: math domain error


I want to define a function that returns the values of the roots. It is supposed to return always something.

If b**2 - 4ac < 0, then it is supposed to return [ ], but it appears as an error.

My code is this by now:

    from math import*
    def solve(a, b, c):
        x = sqrt(b**2 - 4*a*c)

        if x > 0:
           x1 = (-b + x)/(2*a)
           x2 = (-b - x)/(2*a)
           return [x1, x2]

        elif x == 0:
           x1 = x2 = -b/(2*a)
           return [x1]

       else:
           return []

Solution

  • sqrt will not accept negative values. To avoid this, you can check your 'else' condition before computing the square root:

    from math import sqrt
    
    def solve(a, b, c):
        
        formula = b**2 - 4*a*c
    
        if formula < 0:
           return []
    
        x = sqrt(formula)
    
        if x > 0:
           x1 = (-b + x)/(2*a)
           x2 = (-b - x)/(2*a)
           return [x1, x2]
    
        elif x == 0:
           x1 = x2 = -b/(2*a)
           return [x1]