总和中的符号[sympy]

时间:2011-10-27 13:58:25

标签: python sympy

例如,我想解决

http://www.texify.com/img/%5CLARGE%5C%21%5Cdisplayst%5Csum_%7Bn%3D1%7D%5EN%5C%20n%5E2%5C%20%3D%5C%2055.gif

这是我试过的:

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.

2 个答案:

答案 0 :(得分:5)

Python的内置range()函数不了解符号评估。请尝试使用SymPy的sum()函数:

>>> 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

请注意,lambda表达式可能是不必要的,具体取决于您实际想要实现的目标:

>>> 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]

你仍然必须忽略复杂的结果。

答案 1 :(得分:3)

尝试求和函数

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]