Ask Your Question
1

Variable overrites function defined previously

asked 2016-12-27 23:58:06 +0200

omoplata gravatar image

updated 2016-12-28 00:00:46 +0200

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[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
2

answered 2016-12-28 02:26:49 +0200

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')
g
sage: G=SR.var('g')
sage: g(G)
g(g)
sage: diff(g(G),G)
D[0](g)(g)
edit flag offensive delete link more

Comments

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 20:39:07 +0200 )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 23:12:35 +0200 )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

Stats

Asked: 2016-12-27 23:58:06 +0200

Seen: 466 times

Last updated: Dec 28 '16