Reputation: 6259
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?
Upvotes: 1
Views: 304
Reputation: 91680
That's a bug. It ought to work. In general, however, it's best to prefer exact rational numbers over floats in SymPy, wherever possible. If you replace 0.5
with Rational(1, 2)
it works.
Upvotes: 2
Reputation: 16639
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
Upvotes: 3