Programming‎ > ‎Mini-Projects‎ > ‎

01 Quadratic Formula

In this project you will implement the quadratic formula in python to solve for the roots of a quadratic equation. Your program must handle both real and imaginary roots. You are not allowed to use the imaginary math libraries for your computations. Instead, your program must handle checking for imaginary roots and compute them using real numbers, and then format the output appropriately if the roots are indeed imaginary.

This assignment will require you to use a number of important programming concepts and data types, including

 These are difficult concepts to understand in some cases, so don't underestimate how long this program will take.

Specifically your program must do the following:

  1. Use a function that asks the user for the coefficients a, b, and c. The function should verify that the user has entered numeric values for the coefficients.
  2.  Use a function called quad_frm(a, b, c) to return real roots as a tuple such as (1.0, -1.0)
  3. quad_frm(a, b, c) must return complex roots as a tuple of tuples such as ((0, 1.0),(0, -1.0)).
  4. Catch and handle bad user input and other error conditions using exception handling, report error messages as appropriate, and ask the user to re-enter the data.
  5. Use a function that accepts the tuples from quad_frm() and formats and prints the output for the user.
  6. Print the roots as r1=, r2 = if the roots are real
  7. Print the roots as r1 = + i*y.yyy, r2 = - i*y.yyy if the roots are imaginary

 The the following doctest code will make sure your quad_frm() function is working properly..

    >>> quad_frm(1,2,1)
    (-1.0, -1.0)
    >>> quad_frm(1, 0, 1)
    ((0.0, 1.0), (0.0, -1.0))
    >>> quad_frm(1, -1, -6)
    (3.0, -2.0)
    >>> quad_frm(1,-4,13)
    ((2.0, 3.0), (2.0, -3.0)
    >>> quad_frm(2,-1,-1)
    (1.0, -0.5)
Your program must check for valid inputs for a, b, and c and catch runtime errors using exception handling.  If the user enters an improper value for a, b, or c, you must catch the error and exit the program. You may not use any of the built-in complex math functions, i.e., you must handle all the complex number manipulations yourself, using real values. 
You must add pertinent and appropriate remark statements to make your code more readable. For example
if d<0:     # check for imaginary roots
You may use the math library however to get a square-root function.  Use the following

from math import *

This allows you to use sqrt(x) .