Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Sympy Expression is Nan?

Tags:

python

nan

sympy

How do I check if a sympy expression evaluates to nan?

I simply need to do something like this:

if is_nan( expression ):
    #Do stuff
like image 604
D Adams Avatar asked May 31 '16 18:05

D Adams


2 Answers

In sympy, you can check for equality with the sympy nan object:

>>> alpha = sympy.nan
>>> alpha == sympy.nan
True

In numpy, you cannot check for equality with the numpy nan object:

>>> alpha = numpy.nan
>>> alpha == numpy.nan
False
>>> numpy.isnan(alpha)
True

Hence there exists a numpy.isnan() method, and there does not exist a sympy.isnan() method.

Credit to Morgan Thrapp

like image 97
D Adams Avatar answered Sep 17 '22 15:09

D Adams


In SymPy, == always checks structural equality (that is, if two expressions are exactly equal). This works even for nan, so there is no need for a separate isnan function (strictly speaking, SymPy's nan isn't an IEEE 754 nan).

like image 36
asmeurer Avatar answered Sep 17 '22 15:09

asmeurer