What would be wrong with this function that return a rounded number in millions
<p>I'm a beginner doing an online course using ipython notebook and panda.</p>

<p>We are given a function</p>

<pre><code>def roundToMillions (value):
    result = round(value / 1000000)
    return result
</code></pre>

<p>and some tests </p>

<pre><code>roundToMillions(4567890.1) == 5

roundToMillions(0) == 0  # always test with zero...

roundToMillions(-1) == 0 # ...and negative numbers

roundToMillions(1499999) == 1 # test rounding to the nearest
</code></pre>

<p>We are told .. <strong><em>Define a few more test cases for both functions</em></strong> .</p>

<p>I can't think of any more tests though.</p>

<p>The question posed is:</p>

<p><strong><em>Why can't you use roundToMillions() to round the population to millions of inhabitants?</em></strong></p>

<p>I don't quite understand what could be wrong with the function. </p>

<p>This course is free and so there is not really much help available.</p>

<p>In terms of test cases, this loop will generate many test cases and the results speak for themselves:</p>

<pre><code>for x in xrange(-2000000, 2000000, 250000):
print roundToMillions(x), x
&gt;&gt; -2.0 -2000000 
&gt;&gt; -2.0 -1750000
&gt;&gt; -2.0 -1500000
&gt;&gt; -2.0 -1250000
&gt;&gt; -1.0 -1000000
&gt;&gt; -1.0 -750000
&gt;&gt; -1.0 -500000
&gt;&gt; -1.0 -250000
&gt;&gt; 0.0 0
&gt;&gt; 0.0 250000
&gt;&gt; 0.0 500000
&gt;&gt; 0.0 750000
&gt;&gt; 1.0 1000000
&gt;&gt; 1.0 1250000
&gt;&gt; 1.0 1500000
&gt;&gt; 1.0 1750000
</code></pre>

<p>So obviously it's rounding down.</p>

<p>This is due to integer division. removing the round shows this:</p>

<pre><code>def roundToMillions (value):
    result = value / 1000000
    return result
print roundToMillions(999999)
&gt;&gt; 0 
</code></pre>

<p>This is fixed by adding a .0 to the function:</p>

<pre><code>def roundToMillions (value):
    result = round(value / 1000000.0)
    return result

for x in xrange(0, 1000000, 250000):
    print roundToMillions(x), x
&gt;&gt; 0.0 0
&gt;&gt; 0.0 250000
&gt;&gt; 1.0 500000
&gt;&gt; 1.0 750000
print roundToMillions(999999)
&gt;&gt; 1.0
</code></pre>

<p>For more on integer division have a look at </p>

<pre><code>print (3/2)
&gt;&gt; 1
print (3.0/2.0)
&gt;&gt; 1.5
</code></pre>

python pandas