```
#!/bin/env python
"""Quadratic equation solver
PEP8 checked with pep8 --show-source --show-pep8
Takes care of also complex multipliers and zero multiplier corner cases.
by Tony Veijalainen 2011, Freeware (Creative Commons attribution licence)
"""
from __future__ import print_function, division
from cmath import *
delta = 1e-9
def solve_quadratic(a, b, c):
""" a * x **2 + b * x + c solutions
solves solve_quadraticratic equations
"""
if not a:
print('Warning! No second order term in solve_quadratic function.')
return (-c / b,) if b != 0 else (float('inf'),) if c == 0 else (0 / 0,)
discriminant = (b ** 2) - 4 * a * c
# print(discriminant) # debug
if type(discriminant) == type(0 + 1j) or discriminant < 0:
return ((-b + sqrt(discriminant)) / (2 * a),
(-b - sqrt(discriminant)) / (2 * a))
elif discriminant > 0:
return (((-b + sqrt(discriminant)) / (2 * a)).real,
((-b - sqrt(discriminant)) / (2 * a)).real)
else:
return -b / (2 * a), # comma -> singleton tuple
if __name__ == '__main__':
for vals in ((2, 4, -30), (1, 3, 4), (1, 9, 4),
(1, -4, -2), (3, 0, 7), (1, 0, -9),
(3 + 5j, 6 + 8j, 2 + 9j),
(0, 3, -5), (0, 0, -4), (0, 0, 0)):
test = solve_quadratic
print(40 * '-')
print()
print('Testing function %r' % test.__name__)
try:
solutions = test(*vals)
except ZeroDivisionError:
print('No solutions for %s == 0' % (vals[-1],))
else:
for solution in solutions:
a, b, c = vals
print(vals, 'solution', solution)
if solution == float('inf'):
print('Equation allways true!')
else:
print('%s < %g' %
((a * (solution ** 2) + b * solution + c), delta))
assert abs(a * (solution ** 2) + b * solution + c) < delta
```

About the Author

*Edited 5 Years Ago by pyTony*: n/a

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.