Question about sum and diff
Why this code :
f(x)=sum(diff(sin(x),x,n),n,1,10)
f(x)
does not work?
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.
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.
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?
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.
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)
Please start posting anonymously - your entry will be published after you log in or create a new account.
Asked: 9 years ago
Seen: 701 times
Last updated: Feb 06 '15
implicitly defining a sequence of variables
summing over a list of variables?
Detecting series divergence automatically
Taylor expansion twice for a general function cause problem?
Easy (beginner) sum problem:"need a summation variable"?
TypeError: range() integer end argument expected, got sage.symbolic.expression.Expression.