# [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

/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>
pass
</textfield>

<comparisoncode>
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>