[LON-CAPA-cvs] cvs: modules /gerd/programcheck hartz_example.xml

www www at source.lon-capa.org
Thu Nov 17 08:39:46 EST 2011

www		Thu Nov 17 13:39:46 2011 EDT

  Added files:                 
    /modules/gerd/programcheck	hartz_example.xml 
  Example by Adam Hartz

Index: modules/gerd/programcheck/hartz_example.xml
+++ modules/gerd/programcheck/hartz_example.xml
<problem title="More Complex" maxchecks="20">

Try testing your solution to the previous problem with arguments
<tt>quadraticRoots(1, 2, 3)</tt>.  You'll get an error because the
roots of the quadratic equation with those coefficients are
Python actually has complex numbers as a primitive data type.  There
are two ways to make a complex number:
>>> complex(1, 2)
>>> 1+2j
If you want to get the parts out of a complex number, you can do the
>>> thing = complex(1, 2)
>>> thing.imag
>>> thing.real
<i>You're probably used to using <i>i</i> for (-1)<sup>0.5</sup>.  Just to
confuse you, we're going to use <i>j</i> instead.  Why?  Because to an
electrical engineer, <i>i</i> stands for current, and there's no arguing.</i>
Now, write a new procedure <tt>quadraticRootsComplex(a, b, c)</tt>
that computes quadratic roots, as before (including the a=0 case), but works on any real
arguments and returns complex roots if necessary.

<question type="pythoncode" points="10">
def quadraticRootsComplex(a, b, c):

def quadraticRootsComplex(a, b, c):
    if a == 0:
        return -float(c)/float(b)
    a = complex(a, 0)
    b = complex(b, 0)
    c = complex(c, 0)
    det = (b * b - 4 * a * c) ** 0.5
    return [(-b + det) / (2 * a), (-b - det) / (2 * a)]
#any code we would want to run before the student's code goes here

#any code to be run after the student's code (but before the test cases) goes here
import random

<compare>quadraticRootsComplex(0,random.uniform(3,5), random.uniform(6,7))</compare>


More information about the LON-CAPA-cvs mailing list