我对sympy的经验不是很丰富,如果这是一个简单的问题,抱歉。
如何使用sympy扩展二项式表达式?例如,我想让sympy计算多项式$(x ^ 2 + x + 1)^ n $中的$ x ^ 2 $系数(我希望答案为$ n + \ binom {n} {2} $)。
我尝试了以下代码:
x = symbols('x')
n = symbols('n', integer=True, nonnegative = True)
expand((x**2+x+1)**n)
但是结果只是$(x ^ 2 + x + 1)^ n $,而我想要二项式展开式,即。
谢谢。
在这种情况下没有符号扩展,但是stats.joint_rv中的多项式可能会有所帮助。 rsolve
也可以用来表示在x^2
系数中看到的图案的闭合形式:
>>> print([((x**2+x+1)**i).expand().coeff(x**2) for i in range(8)])
[0, 1, 3, 6, 10, 15, 21, 28]
>>> from sympy.abc import n
>>> f=Function('f') # f(n) represents the coefficient of x**2 for a given n
给定x^2
的n
的系数比上一个值大n
:
>>> rsolve(f(n)-f(n-1)-n, f(n),{f(0):0,f(1):1})
n*(n + 1)/2
此最终表达式是任意x^2
的n
系数。