# subs: for function and its derivative

Hello,

if you have an expression like

y=function("y")(x)
f=diff(y,x)+5*y


and would like replace y by x^2,

I would normally call

f.subs(y==x^2).show()

But this only substitutes the y in the second term, but not the function y in the derivative. So, in order to do that I do

f.subs(y==x^2).subs(diff(y,x)==diff(x^2,x)).show()

This works and I can live with this, but I was wondering if there is a "short cut" to replace the function y in the second term as well as the function y in the derivative at the same time?

I am looking for something similar to

(D[y[x],x]+5y[x])/.y->Function[x,x^2]


in Mathematica.

edit retag close merge delete

Sort by ยป oldest newest most voted

For substituting a function, you should use substitute_function, not subs:

sage: y = function('y')
sage: f = diff(y(x), x) + 5*y(x)
sage: y0(x) = x^2
sage: f.substitute_function(y, y0)
5*x^2 + 2*x


Note the definition y = function('y') instead of y = function('y')(x). Of course, you can always introduce some abbreviation for y(x), with a symbol different from y, e.g.

sage: Y = y(x)
sage: f = diff(Y, x) + 5*Y
sage: f.substitute_function(y, y0)
5*x^2 + 2*x

more

In the following code

a=var('a')
y=function('y')
f=diff(y(x),x)+5*y(x)
f.substitute_function(y,a^2).show()


gives 5x^2+2x, where as it should have given 5a^2 since the the differentiation is with respect to x not a.

What I am looking for should look like (after the substitution) :

diff(a^2,x)+5*a^2


In Mathematica this is done by

(D[y[x],x]+5y[x])/.y->Function[x,a^2]


and this gives 5a^2

( 2020-06-10 14:06:28 +0100 )edit

Simply set

y0(x) = a^2


in the code of my answer.

( 2020-06-10 14:27:15 +0100 )edit

Here is the full code:

sage: a = var('a')
sage: y = function('y')
sage: f = diff(y(x), x) + 5*y(x)
sage: y0(x) = a^2
sage: f.substitute_function(y, y0)
5*a^2

( 2020-06-10 14:29:05 +0100 )edit

Interesting. This solves my problem. Thank you. However, left me with many "behind the scene" probems :)

Why doesn't substitute_function work when I define the function y as

y=functioin('y')(x)


?

( 2020-06-10 15:14:40 +0100 )edit

y = function('y')(x) does not define a function, but the symbolic expression y(x), More precisely, it defines the Python variable y as the symbolic expression y(x). Hence y cannot be used as an argument to substitute_function.

( 2020-06-10 16:16:22 +0100 )edit