Math domain error (Python) when calculating sqrt

from math import sqrt


def get_roots(a, b, c):
    discriminant = (b ** 2) - (4 * a * c)
    root1 = (-b - sqrt(discriminant)) / (2 * a)
    root2 = (-b + sqrt(discriminant)) / (2 * a)
    if discriminant > 0:
        return root1, root2
    elif discriminant < 0:
        return None
    else:
        return root1, None

When testing or verifying a function, a message appears stating that in the line

root2 = (-b + sqrt(discriminant)) / (2 * a)

Passes math domain error. The catch? Thank you in advance

Author: jfs, 2017-01-16

2 answers

For real numbers, the root of a negative number does not exist:

>>> import math
>>> math.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error
math domain error

For complex numbers, the root is:

>>> import cmath
>>> cmath.sqrt(-1)
1j
 4
Author: jfs, 2017-01-16 22:08:55

You take the square root of a negative number. Here is the result of running your code on the site(I also inserted print('discriminant:', discriminant)) https://repl.it/FKpS/1

 0
Author: Andrio Skur, 2017-01-16 22:09:54