Ask Your Question

Question about sum and diff

asked 2015-02-06 11:57:46 -0600

Desruim gravatar image

updated 2015-02-06 12:19:33 -0600

tmonteil gravatar image

Why this code :


does not work?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2015-02-06 12:19:18 -0600

tmonteil gravatar image

When you write sum(diff(sin(x),x,n),n,1,10), you try to do a symbolic sum, hence the Python name n should be defined as a symbolic variable (an element of the Symbolic Ring). However, in Sage, the name n corresponds to the function that makes numerical_approx:

sage: n
<function numerical_approx at 0xb3f63684>
sage: n(pi)

This explains why you got the error TypeError: no canonical coercion from <type 'function'> to Symbolic Ring, this is because Sage try (without success) to transform the numerical_approx function into an element of the Symbolic Ring.

So you may try to overwrite the name n to correspond to the symbolic variable "n":

sage: n = SR.var('n')
sage: sum(diff(sin(x),x,n),n,1,10)

But then the result is unexpected ! The problem is that now, when you write diff(sin(x),x,n), Sage does not understands "differentiate n times relative to x", but "differentiate relative to x and then to n", so you get 0 since a function of x has a zero derivative relative to n.

For Sage to understand "differentiate n times relative to x", n needs to be an integer, not a symbol. So, instead you can do a non-symbolic sum of a list that contains all derivatives:

sage: f(x) = sum([diff(sin(x),x,n) for n in range(1,11)])
sage: f(x)
cos(x) - sin(x)

Which seems correct.

edit flag offensive delete link more


Thanks a lot. I didn't know how to tell Sage that n is an integer (I tried assume) and not a symbol. I think I have to learn more about list in Sage. It seems to be a powerful tool.

Desruim gravatar imageDesruim ( 2015-02-06 12:43:50 -0600 )edit

And if I want to build a function which give the nth-derivative of a function g relative to x? That code won't work: 'f(x,n)=diff(g(x),x,n)` How to do that?

Desruim gravatar imageDesruim ( 2015-02-06 12:50:17 -0600 )edit

This currently needs a Python function with a loop (looping over diff). I thought I had a bug report filed for that but can't find it atm.

rws gravatar imagerws ( 2015-02-07 02:52:37 -0600 )edit

No you don't need a loop but a Python function it must be:

sage: def diffn(f,x,n):
....:     return diff(f,x,n)
rws gravatar imagerws ( 2015-02-07 02:55:32 -0600 )edit

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


Asked: 2015-02-06 11:57:46 -0600

Seen: 247 times

Last updated: Feb 06 '15