Reputation: 401
For example, I'd like to solve
(source: texify.com)
Here's what I tried:
from sympy import var, solve
x = var('x')
f = lambda N: sum( n**2 for n in range(1,N+1) )
f(x)
# output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: range() integer end argument expected, got Add.
Upvotes: 2
Views: 4724
Reputation: 57271
Try the summation function
In [1]: n = Symbol('n', real=True)
In [2]: N = Symbol('N', real=True)
In [3]: summation(n**2, (n, 1, N)) # sum n**2 taking n from 1 to N
Out[3]:
3 2
N N N
── + ── + ─
3 2 6
In [4]: solve(summation(n**2, (n, 1, N)) - 55, N)
Out[4]: [5]
Upvotes: 3
Reputation: 601599
Python's built-in range()
function isn't aware of symbolic evaluation. Try using SymPy's sum()
function instead:
>>> from sympy import sum, var, solve
>>> x = var('x')
>>> f = lambda N: sum(n**2, (n, 1, N))
>>> n = var("n")
>>> f(x)
x/6 + x**2/2 + x**3/3
Note that the lambda expression might be unnecessary, depending on you actually want to achieve:
>>> N = var("N")
>>> solve(sum(n**2, (n, 1, N)) - 55, N)
[-13/4 - I*359**(1/2)/4, 5, -13/4 + I*359**(1/2)/4]
You'll still have to ignore the complex results.
Upvotes: 5