Calculating the sum of a series?
<p>This is my assignment and for the life of me i cant seem to think of a way to do it. This is the code I have so far:</p>

<pre><code>sum = 0
k = 1
while k &lt;= 0.0001:
     if k % 2 == 1:
       sum = sum + 1.0/k
     else:
      sum = sum - 1.0/k
 k = k + 1
 print()
</code></pre>

<p>This is my assignment :</p>

<blockquote>
  <p>Create a python program named sumseries.py that does the following:
  Put comments at the top of your program with your name, date, and
  description of what the program does.</p>
  
  <p>Write a program to calculate and display the sum of the series:</p>
  
  <p>1 - 1/2 + 1/3 - 1/4 + ...</p>
  
  <p>until a term is reached that is less than 0.0001.</p>
</blockquote>

<p>The answer with 10,000 iterations appears to be 0.6930971830599583</p>

<p>I ran the program with 1,000,000,000 (billion) iterations and came up with a number of 0.6931471810606472. I need to create a loop to programmably create the series.</p>

<p>Actually, you could write this shorter:</p>

<pre><code>Answer = sum(1.0 / k if k % 2 else -1.0 / k for k in range(1, 10001))
</code></pre>

<hr>

<h3>What this code does:</h3>

<ul>
<li>the innermost part is a <a href="https://wiki.python.org/moin/Generators" rel="nofollow">generator</a> expression, which computes the elements of a series 'on the fly'

<ul>
<li><code>1.0 / k if k % 2 else -1.0 / k</code> results in <code>1.0 / k</code> if <code>k</code> is odd and <code>-1.0 / k</code> otherwise (<code>a - b</code> is the same as <code>a + (-b)</code>)</li>
<li><code>for k in range(1, 10001)</code> goes through all <code>k</code>s in range from 1 (included) to 10001 (excluded)</li>
</ul></li>
<li><a href="https://docs.python.org/3/library/functions.html#sum" rel="nofollow"><code>sum</code></a> can compute the sum of any sequence (any <a href="http://stackoverflow.com/questions/9884132/what-exactly-are-pythons-iterator-iterable-and-iteration-protocols"><em>iterable</em></a>, to be precise), be it a list, a tuple, or a generator expression</li>
</ul>

<hr>

<h3>The same without generator expressions:</h3>

<pre><code>Answer = 0
for k in range(1, 10001):
    if k % 2:
        Answer += 1.0 / k
    else:
        Answer -= 1.0 / k

    # or simply:
    # Answer += 1.0 / k if k % 2 else -1.0 / k
</code></pre>

python python-3.x