# Variable overrites function defined previously

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
u
sage: h
u |--> h(u)
diff(h(u)*u(t),t)
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(h)(u(t))*D(u)(t) + h(u(t))*D(u)(t)


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

edit retag close merge delete

Sort by » oldest newest most voted

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')
g
sage: G=SR.var('g')
sage: g(G)
g(g)
sage: diff(g(G),G)
D(g)(g)

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.

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.