tfv - 1 year ago 62

Python Question

I am trying to evaluate an infinite sum in SymPy. While the first expression is calculated the way I expect it, SymPy seems to have trouble with the second expression.

`from sympy import *`

n = symbols('n')

print Sum((2)**(-n), (n, 1, oo)).doit()

print Sum((0.5)**(n), (n, 1, oo)).doit()

Results in:

`1`

Sum(0.5**n, (n, 1, oo))

I assume that the reason is that I am using a float number instead of an integer value.

Is there a way to approximate the sum instead?

Answer Source

From the docs:

If it cannot compute the sum, it returns an unevaluated Sum object.

Another way to do this would be:

```
In [40]: Sum((Rational(1,2))**(n), (n, 1, oo)).doit()
Out[40]: 1
```

Yet another way to do this:

```
In [43]: Sum((0.5)**(n), (n, 1, float('inf'))).doit()
Out[43]: 1.00000000000000
```

To approximate, you can take a sufficiently large number instead of infinity:

```
In [51]: import sys
In [52]: Sum((0.5)**(n), (n, 1, sys.maxint)).doit()
Out[52]: 1.00000000000000
```