问题
I am using SymPy for symbolic manipulation of expression, which is evaluated on huge amounts of data using NumPy. To speed up things, I use sympy.lambdify, but I cannot get abs to work.
import sympy
import numpy as np
x = sympy.symbols('x',real=True)
def f(x):
return 1-sympy.Abs(x)
def g(x):
return 1-sympy.sqrt(x)
fl = sympy.lambdify(x,f(x),'numpy')
gl = sympy.lambdify(x,g(x),'numpy')
gl(1) # success
gl(np.array([1,2,3]))
fl(2) # NameError: global name 'Abs' is not defined
fl(np.array([1,2,3])) # Same error
An option would be to use the 'sympy' argument for the lambdify call, but then I cannot use arrays. I have tried using sympy.abs and numpy.abs, but without success.
I use it in a program for solving cumbersome integrals using inverse-substitution and some tabulated integrals, but it would be so convenient with the option using an abs function instead of explicitly handling different regions.
sympy.Abs is indeed defined
Thanks in advance
回答1:
This looks like a bug that has been fixed in recent versions of SymPy: https://code.google.com/p/sympy/issues/detail?id=2654 It works on Python 2.7.9, SymPy 0.7.3 and Python 3.3.5, SymPy 0.7.5.
回答2:
You can workaround this by mapping Abs to abs, like lambdify(x, f(x), ["numpy", {'Abs': numpy.abs}]). Of course, upgrading SymPy is a much better solution if it's possible for you.
来源:https://stackoverflow.com/questions/27610844/python-sympy-lambdify-abs-for-use-with-numpy