0

I'd like to calculate an infinite sum

Like this: Sum from k=1 to infinite of (0.9^k) * r + k+1 //or any other

My first idea was something like this:

def infiniteCalc(r):
    result = r
    for k in range(10000000):
        result += 0.9**k + r + k +1 +1 //k is starting at 0, so another +1

    return result

Another idea was to check, if the result changes within an iteration, but I'm not sure if this is helpful.

Another idea was to use something like limit, but I don't know if python provides a function for that (and if, is this really my solution?)

Sadık
  • 4,249
  • 7
  • 53
  • 89
  • What's your expected output? `sum( [1, inf) )` (that's set notation there, not python code) is...? – Adam Smith May 06 '14 at 23:16
  • 3
    That series doesn't converge, so `return float('inf')`. – roippi May 06 '14 at 23:18
  • Minor fix, in order for it to work properly, instead of adding the extra +1, change `range(10000000)` to `range(1,10000000)` – Natecat May 06 '14 at 23:18
  • [There is the `1/(0.1)` formula](http://en.wikipedia.org/wiki/Geometric_series#Formula) – inspectorG4dget May 06 '14 at 23:20
  • If you really want to do the sum and not use SymPy, then you should probably go for `itertools.count` which will continue indefinitely (so you need to break out of the for loop). – Midnighter May 14 '14 at 15:20

2 Answers2

2

It sounds like your objective is to do symbolic execution of expressions, rather than actually wanting to compute it numerically. For this you want a library like SymPy. Here's the reference on summations: http://docs.sympy.org/dev/modules/concrete.html#sympy.concrete.summations.Sum

Alex Gaynor
  • 14,353
  • 9
  • 63
  • 113
1

Here's an example using SymPy with your expression:

>>> from sympy import *
>>> var('r k')
(r, k)
>>> Sum((0.9**k) * r + k + 1,(k,1,oo))
Sum(0.9**k*r + k + 1, (k, 1, oo))
>>> _.doit()
Sum(0.9**k*r + k + 1, (k, 1, oo))
>>> nsimplify(_, rational=True)
Sum((9/10)**k*r + k + 1, (k, 1, oo))
>>> _.doit()
9*r + oo
smichr
  • 16,948
  • 2
  • 27
  • 34