Ask Your Question

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

edit retag close merge delete

## 1 Answer

Sort by » oldest newest most voted

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

more

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2018-03-31 19:34:18 +0200

Seen: 104 times

Last updated: Mar 31 '18