Ask Your Question
1

sum and Substitute

asked 2018-10-01 10:07:21 -0500

ortollj gravatar image

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 flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
2

answered 2018-10-01 11:11:32 -0500

tmonteil gravatar image

updated 2018-10-01 11:12:34 -0500

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.

edit flag offensive delete link more

Comments

Thanks tmonteil

ortollj gravatar imageortollj ( 2018-10-01 11:32:50 -0500 )edit
1

answered 2018-10-01 11:48:46 -0500

Emmanuel Charpentier gravatar image

updated 2018-10-01 11:55:21 -0500

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...).

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-10-01 10:07:21 -0500

Seen: 41 times

Last updated: Oct 01