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>You can also use <code>itertools.accumulate</code> to generate these values:</p>

<pre><code>from itertools import accumulate
for i, ans in enumerate(accumulate(n/(n+1) for n in range(1, 21)), start=1):
    print(str(i).ljust(4), format(ans, '.4f'))
</code></pre>

<p>Output:</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