How to trick SymPy expression containing erf function for use with NumPy

I would like to wrap a symbolic expression containing an erf function using SymPy. This can be done for scalar arguments like this:

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 quote this. I would normally do the following:

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

+5


source to share


2 answers


You said lambdify

that he only had it numpy

as a module for the game; 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

      

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, whichever you want sympy.core.numbers.Float

or float

.

+3


source


Since SymPy 1.3, scipy is automatically supported in lambdify. If you omit the argument modules

, it will automatically add scipy. Or you can use modules=['numpy', 'scipy']

.



>>> 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)
>>> vector_F(1.0, 0.0, 1.0)
0.5

      

0


source







All Articles