Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lambdified Piecewise produces "RuntimeWarning: invalid value encountered in log" #14789

Open
GeorgySk opened this issue Jun 10, 2018 · 2 comments

Comments

@GeorgySk
Copy link

Simple example:

import sympy as sym

x = sym.Symbol('x')
f = sym.Piecewise((sym.log(-x), x < 0),
                  (sym.log(x), True))
lf = sym.lambdify(x, f)
print(lf(10))

gives:

2.302585092994046
/home/georgy/miniconda3/lib/python3.6/site-packages/numpy/__init__.py:1: RuntimeWarning: invalid value encountered in log
  """

Value is calculated correctly, then why is there a warning?

@moorepants
Copy link
Member

Seems like it is evaluating both log(x) and log(-x). But the underlying printer doesn't seem to do this:

In [6]: from sympy.printing import lambdarepr

In [9]: lambdarepr.lambdarepr(f)
Out[9]: '((log(-x)) if (x < 0) else (((log(x)) if (True) else None)))'

In [12]: x = 10

In [13]: ((np.log(-x)) if (x < 0) else (((np.log(x)) if (True) else None)))
Out[13]: 2.3025850929940459

@asmeurer
Copy link
Member

asmeurer commented Jun 13, 2018

You want the NumPyPrinter.

>>> from sympy.printing.pycode import NumPyPrinter
>>> NumPyPrinter().doprint(f)
'numpy.select([numpy.less(x, 0),True], [numpy.log(-x),numpy.log(x)], default=numpy.nan)'

It has to use np.select so that the if-then-else gets vectorized, meaning the "incorrect" branch is always evaluated. This was also the problem with #11306. Is there a better NumPy function we can use with lambdify that doesn't evaluate unused branches, but still works on arrays? Such a function would be more efficient too.

Regarding the issue, the warning can be ignored. The invalid value isn't actually used, assuming your piecewise is setup correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants