More than one module for lambdify in sympy

I am trying to get lambdify to understand in order to expect more than one type of input using the modules keyword argument. According to the lambdify source code ( http://docs.sympy.org/dev/_modules/sympy/utilities/lambdify.html ), this can be done using argument lists, but I cannot do this therefore.

import sympy from sympy import lambdify x,y=sympy.symbols('x y') from sympy.parsing.sympy_parser import parse_expr func=lambdify(x,parse_expr(exp(x)),modules=["numpy","sympy"]) func(array([3,4])) 

gives

 array([ 20.08553692, 54.59815003]) 

but when i try

 func(y) 

I get

 Attribute error:exp 

What am I doing wrong here? Should func accept numpy and sympy types? Any help is appreciated!

+4
source share
2 answers

The documentation says that the modules argument will give more priority to the first ones that appear in this case, which is "numpy" in this case. Therefore, if two modules have the same function, it will always be the first.

Good approach:

 import numpy as np def func(x): if isinstance(x, np.ndarray): return np.exp(x) else: return sympy.exp(x) 
+2
source

Modules do not send or something like that. The way lambdify works is that it creates

 lambda x: exp(x) 

where exp comes from the namespace of the modules (modules) that you have selected. lambdify(x, exp(x), ['numpy', 'sympy']) roughly equivalent

 from sympy import * from numpy import * # Various name replacements for differences in numpy naming conventions, like # asin = arcsin return lambda x: exp(x) 

If you want to provide a custom function that sends messages, you can use something like the example of Saullo Castro. You can also use this with lambdify by providing a dict like

 import numpy as np import sympy def myexp(x): if isinstance(x, np.ndarray): return np.exp(x) else: return sympy.exp(x) func = lambdify(x, exp(x), [{'exp': myexp}, 'numpy']) 

This gives

 >>> func(np.array([1, 2])) array([ 2.71828183, 7.3890561 ]) >>> func(sympy.Symbol('y')) exp(y) 
+2
source

Source: https://habr.com/ru/post/1202407/


All Articles