2

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 []
iacob
  • 20,084
  • 6
  • 92
  • 119
Anonymous
  • 49
  • 1
  • 9

2 Answers2

2

The math.sqrt is undefined for negative numbers and thus returns a ValueError.

If you wish to return the complex square root for negatives, use x**0.5:

x = (b**2 - 4*a*c)**0.5

Alternatively use the cmath.sqrt implementation:

from cmath import sqrt

x = sqrt(b**2 - 4*a*c)
iacob
  • 20,084
  • 6
  • 92
  • 119
Nick Ven
  • 91
  • 1
  • 10
  • I got it, the problem now is that ' ' > ' is not supported between instances of 'complex' and 'int' ', so it means that I would have to change all code, isn't it? Anyway, I don't need the complex root, I only need [ ] as return when b**2 - 4*a*c < 0, but advice appears always. – Anonymous Jun 03 '18 at 22:22
  • well yeah... you'll need to change your code – Nick Ven Jun 03 '18 at 22:26
1

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]
iacob
  • 20,084
  • 6
  • 92
  • 119