Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (a symbolic sum over u as a function of w). However, it would be much more useful 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 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)

like image 345
Mauricio Avatar asked Sep 19 '25 07:09

Mauricio


1 Answers

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

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.

like image 181
Saullo G. P. Castro Avatar answered Sep 21 '25 19:09

Saullo G. P. Castro