如何对包含erf函数的SymPy表达式进行lambdify以与NumPy一起使用

时间:2022-06-23 20:19:58

I would like to lambdify a symbolic expression containing the erf function with SymPy. This can be done for scalar arguments as follows:

我想使用SymPy对包含erf函数的符号表达式进行lambdify。这可以用于标量参数,如下所示:

log_normal = 0.5 + 0.5 * sym.erf((sym.log(x) - mu) / sym.sqrt(2 * sigma**2))
F = sym.lambdify([x, mu, sigma], log_normal)
F(1.0, 0.0, 1.0)

I would like to vectorize the above. Normally I would do as follows...

我想对上述内容进行矢量化。通常我会这样做......

log_normal = 0.5 + 0.5 * sym.erf((sym.log(x) - mu) / sym.sqrt(2 * sigma**2))
vector_F = sym.lambdify([x, mu, sigma], log_normal, modules='numpy')
vector_F(1.0, 0.0, 1.0)

However the above raises a NameError...

但是上面引发了一个NameError ......

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-29-14adde48d4a1> in <module>()
----> 1 vector_F(1.0, 0.0, 1.0)

/Users/drpugh/anaconda/lib/python2.7/site-packages/numpy/__init__.pyc in <lambda>(x, mu,     sigma)

NameError: global name 'erf' is not defined

Is this a bug, or am I missing something trivial?

这是一个错误,还是我错过了一些微不足道的东西?

1 个解决方案

#1


3  

You told lambdify it only had numpy as a module to play with; give it a source for erf. IOW, you have

你告诉lambdify它只有numpy作为一个模块玩;给它一个erf的来源。我有,你有

>>> vector_F = sym.lambdify([x, mu, sigma], log_normal, modules=['numpy'])
>>> vector_F(1.0, 0.0, 1.0)
Traceback (most recent call last):
  File "<ipython-input-10-14adde48d4a1>", line 1, in <module>
    vector_F(1.0, 0.0, 1.0)
  File "<string>", line 1, in <lambda>
NameError: global name 'erf' is not defined

but

>>> vector_F = sym.lambdify([x, mu, sigma], log_normal, modules=['numpy', 'sympy'])
>>> vector_F(1.0, 0.0, 1.0)
0.500000000000000

or

要么

>>> vector_F = sym.lambdify([x, mu, sigma], log_normal, modules=['numpy', 'math'])
>>> vector_F(1.0, 0.0, 1.0)
0.5

or whichever erf you prefer, depending on whether you want a sympy.core.numbers.Float or a float.

或者你喜欢哪个,取决于你是否想要一个sympy.core.numbers.Float或一个浮点数。

#1


3  

You told lambdify it only had numpy as a module to play with; give it a source for erf. IOW, you have

你告诉lambdify它只有numpy作为一个模块玩;给它一个erf的来源。我有,你有

>>> vector_F = sym.lambdify([x, mu, sigma], log_normal, modules=['numpy'])
>>> vector_F(1.0, 0.0, 1.0)
Traceback (most recent call last):
  File "<ipython-input-10-14adde48d4a1>", line 1, in <module>
    vector_F(1.0, 0.0, 1.0)
  File "<string>", line 1, in <lambda>
NameError: global name 'erf' is not defined

but

>>> vector_F = sym.lambdify([x, mu, sigma], log_normal, modules=['numpy', 'sympy'])
>>> vector_F(1.0, 0.0, 1.0)
0.500000000000000

or

要么

>>> vector_F = sym.lambdify([x, mu, sigma], log_normal, modules=['numpy', 'math'])
>>> vector_F(1.0, 0.0, 1.0)
0.5

or whichever erf you prefer, depending on whether you want a sympy.core.numbers.Float or a float.

或者你喜欢哪个,取决于你是否想要一个sympy.core.numbers.Float或一个浮点数。