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>From what I can see you're not keeping track of your total sum anywhere, so just add a <code>total</code> variable before your loop and add to that (I also avoid while loops when a for loop will do the trick):</p>

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

def main():
    total = 0
    for num in range(1, 21):
        ans = frac(num, num+1)
        total += ans
        print(num, "    ", format(ans, ".4f"), 'total=', format(total, ".4f"))
main()
</code></pre>

<p>Output looks like this:</p>

<pre><code>1      0.5000 total= 0.5000
2      0.6667 total= 1.1667
3      0.7500 total= 1.9167
4      0.8000 total= 2.7167
5      0.8333 total= 3.5500
6      0.8571 total= 4.4071
7      0.8750 total= 5.2821
8      0.8889 total= 6.1710
9      0.9000 total= 7.0710
10      0.9091 total= 7.9801
11      0.9167 total= 8.8968
12      0.9231 total= 9.8199
13      0.9286 total= 10.7484
14      0.9333 total= 11.6818
15      0.9375 total= 12.6193
16      0.9412 total= 13.5604
17      0.9444 total= 14.5049
18      0.9474 total= 15.4523
19      0.9500 total= 16.4023
20      0.9524 total= 17.3546
</code></pre>

python add series