Python:SymPy lambdify abs用于NumPy

时间:2021-10-16 20:20:38

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.

我使用SymPy进行表达式的符号操作,使用NumPy对大量数据进行评估。为了加快速度,我使用sympy.lambdify,但我不能让abs工作。

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.

一个选项是对lambdify调用使用'sympy'参数,但是我不能使用数组。我尝试过使用sympy.abs和numpy.abs,但没有成功。

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.

我在一个程序中使用它来解决使用逆替换和一些列表积分的繁琐积分,但是使用abs函数而不是显式处理不同区域的选项会非常方便。

sympy.Abs is indeed defined

sympy.Abs确实是定义的

Thanks in advance

提前致谢

2 个解决方案

#1


2  

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.

这看起来像是在SymPy的最新版本中修复的错误:https://code.google.com/p/sympy/issues/detail?id = 2654它适用于Python 2.7.9,SymPy 0.7.3和Python 3.3.5,SymPy 0.7.5。

#2


1  

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.

你可以通过将Abs映射到abs来解决这个问题,比如lambdify(x,f(x),[“numpy”,{'Abs':numpy.abs}])。当然,如果可能的话,升级SymPy是一个更好的解决方案。

#1


2  

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.

这看起来像是在SymPy的最新版本中修复的错误:https://code.google.com/p/sympy/issues/detail?id = 2654它适用于Python 2.7.9,SymPy 0.7.3和Python 3.3.5,SymPy 0.7.5。

#2


1  

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.

你可以通过将Abs映射到abs来解决这个问题,比如lambdify(x,f(x),[“numpy”,{'Abs':numpy.abs}])。当然,如果可能的话,升级SymPy是一个更好的解决方案。