Ask Your Question
2

Redefine symbolic function even in derivatives

asked 2021-12-17 12:34:35 +0100

keko gravatar image

updated 2021-12-17 13:09:40 +0100

As a simple example, I have the following variables and functions:

r = var('r')
th = var('th', latex_name = '\\theta')

g = function('g')(r, th)

f = g + diff(g,r)

From now on I want to decompose g into g0and g2 as:

g0 = function('g0', latex_name = 'g_0')(r)
g2 = function('g2', latex_name = 'g_2')(r)

g = g0 + cos(th)*g2

If I print f I still get:

$ f = g(r, \theta) + dg(r,\theta)/dr $

So instead, I apply a substitution on g:

f = f.subs(g==g0+cos(th)*g2)

This changes g, but not diff(g,r):

$f = g_0(r) + g_2(r)*\cos(\theta) + dg(r,\theta)/dr$

In order to change also diff(g,r) I have to substitute explicitly the derivative:

f = f.subs(diff(g,r) == diff(g0+cos(th)*g2, r))

My question is the following:

Is there a way I can redefine a function without having to redefine also every single derivative? This way, I would avoid having to write all these substitutions:

diff(g,r)     ==   diff(g0+g2*cos(th), r),
diff(g,r,r)   ==   diff(g0+g2*cos(th), r, r),
diff(g,th)    ==   diff(g0+g2*cos(th), th),
diff(g,th,th) ==   diff(g0+g2*cos(th), th, th),
diff(g,th,r)  ==   diff(g0+g2*cos(th), th, r),
diff(g,r,th)  ==   diff(g0+g2*cos(th), r,  th)
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-12-17 14:02:48 +0100

eric_g gravatar image

You should use substitute_function, not subs, having first defined g0*cos(th) + g2 as a function of (th, r):

sage: G(r, th) = g0 + cos(th)*g2
sage: f = f.substitute_function(function('g'), G)
sage: f
cos(th)*g2(r) + cos(th)*diff(g2(r), r) + g0(r) + diff(g0(r), r)

Note that the first argument of substitute_function has to be function('g') because in the declaration g = function('g')(r, th), you have overwritten the Python variable g by the expression function('g')(r,th). It would have been better to keep the Python name g for function('g'), i.e. to write

sage: g = function('g')
sage: f = g(r, th) + diff(g(r, th), r)

Then you can use simply g as the first argument of substitute_function::

sage: f.substitute_function(g, G)
cos(th)*g2(r) + cos(th)*diff(g2(r), r) + g0(r) + diff(g0(r), r)
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: 2021-12-17 12:34:35 +0100

Seen: 331 times

Last updated: Dec 17 '21