Python: SymPy lambdify abs for use with NumPy

ぃ、小莉子 提交于 2019-12-11 04:39:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!