954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

PEP8 Quadratic Equations Solver

0
By Tony Veijalainen on Mar 31st, 2011 3:14 pm

This is hopefully example of properly tested code snippet (fingers crossed).

#!/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

Anybody has drawn picture of x**2 in complex numbers domain? Just curious.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Using color for one coordinate was best I could find:
http://mpmath.googlecode.com/svn/gallery/gallery.html

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

tonyjv, nice images there. For what it's worth, converting to polar coordinates is interesting:
If A = (a + bi) = (a, b) = (R, theta)
where R = sqrt(a^2 + b^2) and theta = atan2(b, a)
(and thus, a = R*cos(theta) and b = R*sin(theta))
then A^2 = (R^2, 2*theta)

raptr_dflo
Practically a Master Poster
602 posts since Aug 2010
Reputation Points: 76
Solved Threads: 82
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: