本文介绍了如何将包含erf函数的SymPy表达式与NumPy一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用SymPy对包含erf函数的符号表达式进行lambd化.可以对标量参数执行以下操作:

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

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)

但是上面提到了NameError ...

However the above raises a 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?

推荐答案

您告诉lambdify它只有numpy作为模块可以使用;为它提供erf的来源. IOW,你有

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

>>> 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

但是

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

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

或您喜欢的任何erf,具体取决于您要的是sympy.core.numbers.Float还是float.

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

这篇关于如何将包含erf函数的SymPy表达式与NumPy一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:14