Ask Your Question

subs: for function and its derivative

asked 2020-06-10 04:05:24 +0200

curios_mind gravatar image


if you have an expression like


and would like replace y by x^2,

I would normally call


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


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


in Mathematica.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2020-06-10 10:32:41 +0200

eric_g gravatar image

updated 2020-06-10 10:35:50 +0200

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
edit flag offensive delete link more


In the following code


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) :


In Mathematica this is done by


and this gives 5a^2

curios_mind gravatar imagecurios_mind ( 2020-06-10 14:06:28 +0200 )edit

Simply set

y0(x) = a^2

in the code of my answer.

eric_g gravatar imageeric_g ( 2020-06-10 14:27:15 +0200 )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)
eric_g gravatar imageeric_g ( 2020-06-10 14:29:05 +0200 )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



curios_mind gravatar imagecurios_mind ( 2020-06-10 15:14:40 +0200 )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.

eric_g gravatar imageeric_g ( 2020-06-10 16:16:22 +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


Asked: 2020-06-10 04:05:24 +0200

Seen: 687 times

Last updated: Jun 10 '20