# Question about sum and diff

Why this code :

f(x)=sum(diff(sin(x),x,n),n,1,10)
f(x)


does not work?

edit retag close merge delete

Sort by ยป oldest newest most voted

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


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


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.

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.

( 2015-02-06 19:43:50 +0200 )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?

( 2015-02-06 19:50:17 +0200 )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.

( 2015-02-07 09:52:37 +0200 )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)
`
( 2015-02-07 09:55:32 +0200 )edit