[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 
  Log:
  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
complex.  
<p>
Python actually has complex numbers as a primitive data type.  There
are two ways to make a complex number:
<pre>
>>> complex(1, 2)
(1+2j)
>>> 1+2j
(1+2j)
</pre>
If you want to get the parts out of a complex number, you can do the
following:
<pre>
>>> thing = complex(1, 2)
>>> thing.imag
2.0
>>> thing.real
1.0
</pre>
<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>
<p>
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">
<initial>
def quadraticRootsComplex(a, b, c):
    #YOUR CODE HERE
    pass
<initial>

<solution>
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)]
</solution>
    
<test>
<pre>
#any code we would want to run before the student's code goes here
</pre>

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

<compare>quadraticRootsComplex(0,random.uniform(3,5), random.uniform(6,7))</compare>
<compare>set(quadraticRootsComplex(1,-2,3))</compare>
<compare>set(quadraticRootsComplex(1,2,3))</compare>
</test>
</question>

</problem>




More information about the LON-CAPA-cvs mailing list