First time here? Check out the FAQ!

Ask Your Question
1

sum and Substitute

asked 6 years ago

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)
Preview: (hide)

2 Answers

Sort by » oldest newest most voted
2

answered 6 years ago

tmonteil gravatar image

updated 6 years ago

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.

Preview: (hide)
link

Comments

Thanks tmonteil

ortollj gravatar imageortollj ( 6 years ago )
1

answered 6 years ago

Emmanuel Charpentier gravatar image

updated 6 years ago

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

Preview: (hide)
link

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: 6 years ago

Seen: 989 times

Last updated: Oct 01 '18