ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sat, 31 Mar 2018 13:17:07 -0500function created in python under sagehttp://ask.sagemath.org/question/41847/function-created-in-python-under-sage/ Below a function in python,
forget();var('n i');g(x)=sin(x)+tan(x);
def maderive(n):
for i in range(n):
g=g.diff()
return g
When I call this function
maderive(3)
It doesn't work, I've got an error .Sat, 31 Mar 2018 12:34:18 -0500http://ask.sagemath.org/question/41847/function-created-in-python-under-sage/Answer by slelievre for <p>Below a function in python,</p>
<pre><code>forget();var('n i');g(x)=sin(x)+tan(x);
def maderive(n):
for i in range(n):
g=g.diff()
return g
</code></pre>
<p>When I call this function </p>
<pre><code>maderive(3)
</code></pre>
<p>It doesn't work, I've got an error .</p>
http://ask.sagemath.org/question/41847/function-created-in-python-under-sage/?answer=41849#post-id-41849There is no need to define such a function.
No need for `var('n i')` either, by the way.
Once you have defined the function `g` by
sage: g(x) = sin(x) + tan(x)
you can check that `g` is a function, and `g(x)` is the corresponding expression:
sage: g
x |--> sin(x) + tan(x)
sage: g(x)
sin(x) + tan(x)
and then you can differentiate the function or the expression three times.
The only thing is that the variable with respect to which to differentiate must be specified.
sage: g.diff(x, 3)
x |--> 4*(tan(x)^2 + 1)*tan(x)^2 + 2*(tan(x)^2 + 1)^2 - cos(x)
sage: g(x).diff(x, 3)
4*(tan(x)^2 + 1)*tan(x)^2 + 2*(tan(x)^2 + 1)^2 - cos(x)
If however you want to understand the error you were getting, here is a hint.
When you do `g = g.diff()` inside a function, it wants to use a local variable `g`
inside the function.
If you want to use a globally defined variable, specify it with `global g` as follows:
sage: def maderive(n):
....: global g
....: for i in range(n):
....: g=g.diff()
....: return g
....:
sage: maderive(3)
x |--> 4*(tan(x)^2 + 1)*tan(x)^2 + 2*(tan(x)^2 + 1)^2 - cos(x)
Note that this modifies the function `g`. After running the above, you get:
sage: g
x |--> 4*(tan(x)^2 + 1)*tan(x)^2 + 2*(tan(x)^2 + 1)^2 - cos(x)Sat, 31 Mar 2018 13:17:07 -0500http://ask.sagemath.org/question/41847/function-created-in-python-under-sage/?answer=41849#post-id-41849