Python code to sum a series incrementally
<p>Great site, and I really appreciate all the answers and tips I get from here. I'm trying to calculate the sum of a series INCREMENTALLY of fractions, but cant seem to get the loop-in-a-function right. I have been able to write the program to calculate the total sum, and to calculate the individual fractions in the series, but I need it to display the running sum at each step in the string. the series is 1/2, 2/3, 3/4, 4/5, ...., 20/21. so that it displays:
0.5000
1.1667
...
16.4023
17.3546</p>

<p>This is what I have so far:</p>

<pre><code>def frac(n, d):
    a = n / d
    return a

def main():
    count = 1
    while count &lt;= 20:
        num = count
        den = count +1
        ans = frac(num, den)
        print(num, "    ", format(ans, ".4f"))
        count += 1
main()
</code></pre>

<p>But it only gives me this:</p>

<pre><code>1      0.5000
2      0.6667
3      0.7500
4      0.8000
5      0.8333
6      0.8571
7      0.8750
8      0.8889
9      0.9000
10     0.9091
11     0.9167
12     0.9231
13     0.9286
14     0.9333
15     0.9375
16     0.9412
17     0.9444
18     0.9474
19     0.9500
20     0.9524
</code></pre>

<p>As many pointed out already, you missed out the accumulation of partial sums in your loop. Now, geeking out a little bit, and using list comprehensions, the same can be achieved like this:</p>

<pre><code>fractions = [ float(x)/(x+1) for x in range(1,21) ]
cumulatives = [sum(fractions[0:i+1]) for i,j in enumerate(fractions)]

for i,item in enumerate(cumulatives):
    print '{} {:.4f}'.format(i+1, item)
</code></pre>

<p>This is in python 2.7. Python 3.x <code>itertools</code> has function <code>accumulate</code>.
See it in action here: <a href="https://eval.in/658781" rel="nofollow">https://eval.in/658781</a></p>

<pre><code>1 0.5000
2 1.1667
3 1.9167
4 2.7167
5 3.5500
6 4.4071
7 5.2821
8 6.1710
9 7.0710
10 7.9801
11 8.8968
12 9.8199
13 10.7484
14 11.6818
15 12.6193
16 13.5604
17 14.5049
18 15.4523
19 16.4023
20 17.3546
</code></pre>

python add series