# sum and Substitute

Hi

why Ds (like D ) does not give a numerical value ?

fs_d=r"!n \triangleq n! \sum_{i = 0}^{n}\frac{(-1)^i}{i!}"
#https://en.wikipedia.org/wiki/Derangement
forget()
var('n,l')
assume(l, 'integer')
assume(l>0)
assume(l, 'integer')
assume(n, 'integer')
assume(n>l)
assume(n, 'integer')
# Derangement
D=function('D')(n,l)
Dn=function('Dn')(n,l)
Dn=factorial(n)*sum(((-1)^l/factorial(l)),l,0,n)
D=factorial(7)*sum(((-1)^l/factorial(l)),l,0,7)
Ds=Dn.substitute({n:7})
show(LatexExpr(fs_d))
show('D : ',D)
show('Ds : ',Ds)

edit retag close merge delete

Sort by ยป oldest newest most voted

The reason is that Sage considers that Ds still has one variable, though it is a dummy one:

sage: Ds
t5040*sum((-1)^l/factorial(l), l, 0, 7)
sage: Ds.variables()
(l,)


You can solve this issue by simplifying the expression:

sage: Ds.simplify_full()
1854


By the way, please note that the lines:

D=function('D')(n,l)
Dn=function('Dn')(n,l)


are useless, since D and Dn are overwritten just after.

more

Thanks tmonteil

( 2018-10-01 11:32:50 -0600 )edit

The symbolic sum sum(((-1)^l/factorial(l)),l,0,n) is not "spontaneously" evaluated. You might force that by using the numerical_approximation method (but this gives you a float where an exact (Integer) result is available).

EDIT : tmonteil types faster than I do. My answer was a bit late, but quasi-identical to Thierry's, which is the simplest solution.

Another workaround is to convert this expression to a Sympy expression, and force its evaluation via the doit method :

sage: Dn
factorial(n)*sum((-1)^l/factorial(l), l, 0, n)
sage: Dn.subs(n=7)
5040*sum((-1)^l/factorial(l), l, 0, 7)
sage: Dn.subs(n=7)._sympy_()
5040*Sum((-1)**l/factorial(l), (l, 0, 7))
sage: Dn.subs(n=7)._sympy_().doit()
1854


BTW, this workaround may help in cases where Sage's simplify fails to find an answer (it happens...).

more