math.sqrt
only works for non-negative values. Either verify that b**2 - 4*a*c >= 0
before calling math.sqrt
, or use cmath.sqrt
instead to handle complex roots.
>>> math.sqrt(-4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
>>> cmath.sqrt(-4)
2j
Note that if you use cmath.sqrt
, printing the value becomes a little more complicated, since there is no format specifier for complex values; you need to extract the real and imaginary parts (root1.real
and root1.imag
) and format them separately.