变量符号数量上乘积的偏导数之和 [英] Sum of partial derivatives of a product over a symbolic number of variables
问题描述
我希望SymPy评估如下表达式:
I would like SymPy to evaluate an expression like the following:
我将如何定义符号和表达式,以便SymPy能够很好地处理它?我想将N
保留为一个符号,即不制作x
的实际有限列表.我已经尝试了IndexedBase
和Sum
/Product
的各种组合,但是没有使其正常工作.
How would I define the symbols and the expression so that SymPy could handle it nicely? I would like to keep N
as just a symbol, i.e. not make an actual finite list of x
's. I have tried various combinations of IndexedBase
and Sum
/Product
, but didn't get it working right.
推荐答案
理想情况是:
x = IndexedBase("x")
i, j, N = symbols("i j N")
expr = Sum(Product(exp(-x[j]**2), (j, 1, N)).diff(x[i]), (i, 1, N))
到目前为止,这是未评估的,expr是
So far this is unevaluated, expr is
Sum(Derivative(Product(exp(-x[j]**2), (j, 1, N)), x[i]), (i, 1, N))
可以使用方法doit
对其进行评估.不幸的是,产品的差异化尚不能奏效:expr.doit()
退货
The method doit
can be used to evaluate it. Unfortunately the differentiation of a product doesn't quite work yet: expr.doit()
returns
N*Derivative(Product(exp(-x[j]**2), (j, 1, N)), x[i])
将乘积重写为求和前的总和有帮助:
Rewriting the product as the sum prior to differentiation helps:
expr = Sum(Product(exp(-x[j]**2), (j, 1, N)).rewrite(Sum).diff(x[i]), (i, 1, N))
expr.doit()
返回
Sum(Piecewise((-2*exp(Sum(log(exp(-x[j]**2)), (j, 1, N)))*x[i], (1 <= i) & (i <= N)), (0, True)), (i, 1, N))
这是区分的正确结果.可悲的是,我们在Piecewise中有一个无关紧要的条件,并且log(exp(...))
应该已经简化了. SymPy不会从外部总和的上下文中推断出(1 <= i) & (i <= N)
是True,并且还犹豫要简化log(exp
,以为x[j]
可能很复杂.因此,我采用分段方式求助于外科手术,将其替换为第一部分,并强行扩大原木:
which is the correct result of differentiation. Sadly we have that extraneous condition in Piecewise, and also log(exp(...))
that should have been simplified. SymPy doesn't infer that (1 <= i) & (i <= N)
is True from the context of the outer sum, and it also hesitates to simplify log(exp
thinking x[j]
might be complex. So I resort to surgical procedure with Piecewise, replacing it by the first piece, and to forcefully expanding logs:
e = expr.doit()
p = next(iter(e.atoms(Piecewise)))
e = expand_log(e.xreplace({p: p.args[0][0]}), force=True)
现在e
是
Sum(-2*exp(Sum(-x[j]**2, (j, 1, N)))*x[i], (i, 1, N))
很遗憾,无法使exp(Sum(..))
再次成为产品.
Couldn't get exp(Sum(..))
to become a Product again, unfortunately.
这篇关于变量符号数量上乘积的偏导数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!