2

I found documentation for lambdify on the sympy website here: http://docs.sympy.org/dev/modules/utilities/lambdify.html

Trying examples with complex numbers seems to fall apart:

SympyExpression = sympy.parsing.sympy_parser.parse_expr('0.2*exp(1.6*I*pi*x)*log(x - 1.5)')
print "\nSympyExpression.subs(sympy.Symbol('x'), 0.0):"
print SympyExpression.subs(sympy.Symbol('x'), 0.0)

PythonFunction = sympy.lambdify((sympy.Symbol('x')), SympyExpression, "numpy")
print "\nPythonFunction(0.0):"
print PythonFunction(0.0)

>>>> SympyExpression.subs(sympy.Symbol('x'), 0.0):
>>>> 0.0810930216216329 + 0.2*I*pi

>>>> PythonFunction(0.0):
>>>> /usr/lib/python2.7/dist-packages/numpy/__init__.py:1: RuntimeWarning: invalid value encountered in log
>>>>   """
>>>> (nan+nan*j)

Did I do something stupid or is this a Bug?

D A
  • 3,130
  • 4
  • 25
  • 41

1 Answers1

3

NumPy's log function requires complex dtype for negative real values, or else it returns nan. From the documentation:

For real-valued input data types, log always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.

To get what you want, either pass in a numpy array with dtype=complex, or pass in 0j, i.e., an explicitly complex typed 0. For other real values, pass in, for instance, 1.0+0j instead of 1.0.

In [36]: lambdify(x, 0.2*exp(1.6*I*pi*x)*log(x - 1.5), 'numpy')(0.0j)
Out[36]: (0.081093021621632885+0.62831853071795862j)
asmeurer
  • 86,894
  • 26
  • 169
  • 240