Ask Your Question
1

function created in python under sage

asked 2018-03-31 12:34:18 -0500

Stu gravatar image

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 flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2018-03-31 13:17:07 -0500

slelievre gravatar image

updated 2018-03-31 13:21:20 -0500

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)
edit flag offensive delete link more

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

Stats

Asked: 2018-03-31 12:34:18 -0500

Seen: 32 times

Last updated: Mar 31