Search code examples
pythonsympynanexponentinfinity

Sympy returning NaN values when substituting infinity into expression


I'm trying to use Sympy to show what happens to terms in a matrix as a variable t tends to infinity.

For example.

from sympy import *
t = Symbol('t')
exp(-t).subs({t: oo})

returns 0 which is correct and

exp(t).subs({t: oo})

returns oo (infinity) which is also correct.

However, some expressions return nan. For example:

(t*exp(-t)).subs({t: oo})

I'm pretty sure above expression should return 0. (N(100*exp(-100)) returns 3.72007597602084e-42).

Is this a bug or is it really 'Not a Number'?


Solution

  • When you have oo*0 the result will be NaN. For some expressions like x**2*exp(-x) there can be a well defined limit as x goes to infinity. But if SymPy doesn't know what the expression is then it can't know how to evaluate oo*0. Consider the following (all examples of 0*oo):

    In [1]: (x*exp(-x)).limit(x, oo)                                                                                                                              
    Out[1]: 0
    
    In [2]: (x**2*exp(-x)).limit(x, oo)                                                                                                                           
    Out[2]: 0
    
    In [3]: (factorial(x)*exp(-x)).limit(x, oo)                                                                                                                   
    Out[3]: ∞
    
    In [4]: (exp(x)*exp(-x)).limit(x, oo)                                                                                                                         
    Out[4]: 1
    

    If you want to calculate a well defined limit then use the limit function/method. Otherwise 0*oo is not well defined so it will evaluate to NaN.