python - Creating a callable with numexpr -


i'm doing symbolic math sympy, generating python lambda function using eval , sympy's lambdastr utility. here's simplified example of mean:

import sympy import numpy np sympy.utilities.lambdify import lambdastr  # simple example expression (my use-case more complex) expr = sympy.s('b*sqrt(a) - a**2') a, b = sorted(expr.free_symbols, key=lambda s: s.name)  func = eval(lambdastr((a,b), expr), dict(sqrt=np.sqrt))  # call func on numpy arrays foo, bar = np.random.random((2, 4)) print func(foo, bar) 

this works, don't use of eval, , sympy doesn't generate computationally-efficient code. instead, i'd use numexpr, seems perfect use-case:

import numexpr print numexpr.evaluate(str(expr), local_dict=dict(a=foo, b=bar)) 

the problem i'd generate callable (like func lambda), instead of calling numexpr.evaluate every time. possible?

you can make use of lambdify module, allows transform sympy expressions lambda functions efficient calculation. nice in ability return function attached implementation.

lambdifying own function this:

func = lambdify((a,b),expr, dict(sqrt=np.sqrt)) 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -