Ask Your Question

Variable overrites function defined previously

asked 2016-12-27 16:58:06 -0500

omoplata gravatar image

updated 2016-12-27 17:00:46 -0500

I have u(t) which is an function of t, and g(u) which is a function of u. I want to find the derivative of g(u)*u(t) w.r.t. t.

sage: u(t) = function('u')(t)
sage: h(u) = function('h')(u)
sage: u
sage: h
u |--> h(u)

This seems to happen because the function u is overwritten when I use u to define the function h. I can get around it this way.

sage: u(t) = function('u')(t)
sage: h(x) = function('h')(x)
sage: u
t |--> u(t)
sage: h
x |--> h(x)
sage: diff(h(u)*u(t),t)
u(t)*D[0](h)(u(t))*D[0](u)(t) + h(u(t))*D[0](u)(t)

Can this be classified as a bug? If it is, would it be possible to fix it?

Thanks in advance.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2016-12-27 19:26:49 -0500

nbruin gravatar image

No this is not a bug. It's just a name clash. It's documented that the notation

   u(t)= ...

binds t to a symbolic variable as well as binds u to the right hand side.

As far as sage is concerned you could have a symbolic function with print name u as well as a symbolic variable with print name u. However, maxima does not support that, so you'd run into problems pretty quickly. It also doesn't add to clarity for the human reader:

sage: function('g')
sage: G=SR.var('g')
sage: g(G)
sage: diff(g(G),G)
edit flag offensive delete link more


Thanks for clarifying.

But I wasn't TRYING to make a function and variable with the same name. My point is that a beginning user who is unfamiliar with Sage could easily overwrite the function he previously defined with a variable. If this possible cause for error was covered, this is one subtlety that one does not have keep in mind while learning Sage.

omoplata gravatar imageomoplata ( 2016-12-28 13:39:07 -0500 )edit

I also think that the multiple side-effects of f(x)=... make it a questionable construct. It's convenient notation for simple examples, but as you show the convenience quickly breaks down in slightly more complicated examples. It's not standard python syntax. See:

sage: preparse("f(x,y)=x+1")
'__tmp__=var("x,y"); f = symbolic_expression(x+Integer(1)).function(x,y)'

Reducing the side effects (by, for instance, removing the "var" part) woud seriously reduce the usefulness of the construct for simple examples. I would just not encourage its use beyond tiny examples, and just consider it a crutch for people who are not really meant to learn sage and do more complicated things with it.

nbruin gravatar imagenbruin ( 2016-12-28 16:12:35 -0500 )edit

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


Asked: 2016-12-27 16:58:06 -0500

Seen: 35 times

Last updated: Dec 27 '16