# Sum SymPy expression over NumPy array

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 (symbolic sum over `u`

as a function `w`

). However, it would be much more convenient to write

``````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 happening? Is there a way to get the amount I want? (Sympy has several ways to sum over integers, but I haven't found one for arrays) (Version: Python 2.7.6, NumPy 1.8.1, SymPy 0.7.4.1)

+3

source to share

The problem is that `f`

there is no value for everyone `k`

. Try it:

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

```

and it will give you the correct result. Where is `subs()`

used to force an estimate `f`

for each value `k`

.

+2

source

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

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

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

```
0

source

All Articles