The problems are here:
- operator precedence: your
/2*a
should be/(2*a)
to work correctly. - the domain of
sqrt
:math.sqrt
bails on negative numbers. - Edit 2:
y = ...
just afterprint "or"
should bex = ...
To fix the latter, you'll need some sort of conditional:
disc = b**2 - 4*a*c
sqrtdisc = math.sqrt(disc) if disc >= 0 else math.sqrt(-disc)*1j
Edit: You could also use cmath.sqrt
, which automatically handles negative numbers:
disc = b**2 - 4*a*c
sqrtdisc = cmath.sqrt(disc)
(Thanks to various other answerers for effectively letting me know that cmath
exists.)