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

www www at source.lon-capa.org
Thu Nov 17 08:53:12 EST 2011


www		Thu Nov 17 13:53:12 2011 EDT

  Added files:                 
    /modules/gerd/programcheck	hartz_example.problem 
  Log:
  Translated Hartz Example
  
  

Index: modules/gerd/programcheck/hartz_example.problem
+++ modules/gerd/programcheck/hartz_example.problem
<problem>
<startouttext />
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.
<endouttext />

<coderesponse type="pythoncode">
<textfield>
def quadraticRootsComplex(a, b, c):
    #YOUR CODE HERE
    pass
</textfield>

<answer>
<comparisoncode>
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)]
</comparisoncode>

<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>
</answer>
</coderesponse>
</problem>




More information about the LON-CAPA-cvs mailing list