Categories

# Complex Solutions to Quadratic Equations

In my previous post I looked at finding real solutions to a quadratic equation. But what about if we wanted to find complex solutions as well.

Luckily it seems to be very easy we just need to import the complex math module using cmath. To be annoying Python uses j rather than i for $\sqrt(-1)$, but I guess we can live with that.

So the code simply becomes:

import math, cmath
print('Quadratic Solver - ax\u00B2 + bx + c = 0')
a = float(input('a: '))
b = float(input('b: '))
c = float(input('c: '))
d = math.pow(b,2)-4*a*c
s1 = (-b+cmath.sqrt(d))/(2*a)
s2 = (-b-cmath.sqrt(d))/(2*a)
print(s1)
print(s2)

We can also give the solutions in modulus argument form for a bit of variation.

import math, cmath
print('Quadratic Solver - ax\u00B2 + bx + c = 0')
a = float(input('a: '))
b = float(input('b: '))
c = float(input('c: '))
d = math.pow(b,2)-4*a*c
s1 = (-b+cmath.sqrt(d))/(2*a)
s2 = (-b-cmath.sqrt(d))/(2*a)
print('Solution 1')
print('Rectangular Coordinates =', s1)
print('Modulus =', abs(s1))
print('Argument =', cmath.phase(s1))
print('Solution 2')
print('Rectangular Coordinates =', s2)
print('Modulus =', abs(s2))
print('Argument =', cmath.phase(s2))