SymPy doit returns NaN instead of zero

17 views
Skip to first unread message

Hadas Biran

unread,
Aug 3, 2022, 2:26:54 PM8/3/22
to sympy

I'm trying to evaluate a long expression with lots of summations and n choose k's. For some reason, the following expression (which is a part of the long expression) returns NaN.

from sympy import *
w_1_2_3 = symbols('w_1_2_3')
w_1_3 = symbols('w_1_3')
w_2_3 = symbols('w_2_3')
w_1_2 = symbols('w_1_2')
exprr = 7*Sum(binomial(5, w_1_2_3)*Sum(binomial(0, -w_1_2_3 + w_1_3)*binomial(2, w_1_2_3 - w_1_3 - 2)*binomial(13, 11 - w_1_2_3), (w_1_3, w_1_2_3, 5)), (w_1_2_3, 0, 5))/868017280
exprr.doit() -> NaN

However, if I evaluate each of the terms in the first sum separately, I get 0 for each of them (as should be):

exprr2 = binomial(5, w_1_2_3)*Sum(binomial(0, -w_1_2_3 + w_1_3)*binomial(2, w_1_2_3 - w_1_3 - 2)*binomial(13, 11 - w_1_2_3), (w_1_3, w_1_2_3, 5))
for t in range(0, 6):
      res = exprr2.subs(w_1_2_3, t).doit()
      print(t, res) 
-> 0 0 
     1 0 
     2 0 
     3 0 
     4 0 
     5 0

What is going on here? Why do I get NaN for the overall term?

I also posted a question in StackOveflow-https://stackoverflow.com/questions/73222278/sympy-doit-returns-nan-instead-of-zero

Aaron Meurer

unread,
Aug 3, 2022, 4:20:52 PM8/3/22
to sy...@googlegroups.com
I'd say this is a bug. The problem it it's evaluating the inner sum to
an expression that has terms like (w_1_2_3 - 1) in both the numerator
and denominator without cancelling them. You can work around it by
evaluating and simplifying the inner summand separately:

>>> 7*Sum((binomial(5, w_1_2_3)*Sum(binomial(0, -w_1_2_3 + w_1_3)*binomial(2, w_1_2_3 - w_1_3 - 2)*binomial(13, 11 - w_1_2_3), (w_1_3, w_1_2_3, 5)).doit()).simplify(), (w_1_2_3, 0, 5)).doit()/868017280
0

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/bd9abc43-562c-4ce1-8561-310e2b97dfdcn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages