在NumPy数组上汇总SymPy表达式

时间:2020-11-30 21:32:52

So, if I do this

所以,如果我这样做

import sympy as sp
import numpy as np
u = np.random.uniform(0, 1, 10)
w, k = sp.symbols('w k')
l = sum(1 - sp.log(k + w) + sp.exp(k + w) for k in u)

I get what I want (a symbolic sum over u as a function of w). However, it would be much more useful to write

我得到了我想要的东西(作为w的函数的象征性的总和)。但是,编写它会更有用

f = 1 - sp.log(k + w) + sp.exp(k + w)
l = sum(f for k in u)

But then I get

但后来我明白了

10*exp(k + w) - 10*log(k + w) + 10

What's going on? Is there a way to get the sum I want? (SymPy has several ways of summing over integers, but I haven't found one for arrays) (Version: Python 2.7.6, NumPy 1.8.1, SymPy 0.7.4.1)

这是怎么回事?有没有办法得到我想要的金额? (SymPy有几种求和整数的方法,但我没有找到一个用于数组的方法)(版本:Python 2.7.6,NumPy 1.8.1,SymPy 0.7.4.1)

2 个解决方案

#1


2  

The problem is that f is not being evaluated for each k. Try this out:

问题是没有为每个k评估f。试试这个:

sum([f.subs(dict(k=k)) for k in u])

and it will give you the right result. Where subs() is being used to force the evaluation of f for each value of k.

它会给你正确的结果。其中subs()用于强制评估每个k值的f。

#2


0  

Making f a function that returns the resulting calculation is what needs to happen here to make it work the way you have it.

使f成为返回结果计算的函数是需要在此处进行的,以使其按照您的方式工作。

f = lambda k,w : 1 - sp.log(k + w) + sp.exp(k + w)

l = sum(f(k,w) for k in u)

#1


2  

The problem is that f is not being evaluated for each k. Try this out:

问题是没有为每个k评估f。试试这个:

sum([f.subs(dict(k=k)) for k in u])

and it will give you the right result. Where subs() is being used to force the evaluation of f for each value of k.

它会给你正确的结果。其中subs()用于强制评估每个k值的f。

#2


0  

Making f a function that returns the resulting calculation is what needs to happen here to make it work the way you have it.

使f成为返回结果计算的函数是需要在此处进行的,以使其按照您的方式工作。

f = lambda k,w : 1 - sp.log(k + w) + sp.exp(k + w)

l = sum(f(k,w) for k in u)