# Replacing functions in a equation

I want to be able to replace a function within a equation. I find a solution for the function R in the given example, and I want to replace R in the equation, hence R=Rsol, where Rsol is a specific function. But it does not seem to replace the function in de2 at all, what am I doing wrong?

var('Rq,k,K')
M=function('M')(x)
R=function('R')(x)
de2=diff(R)==-K(R-Rq)
de1 = diff(M) == -k(M - R)
Rsol=desolve(de2(k=1,K=2,Rq=20),R,ics=[0,15])
Msol=desolve(de1(k=1,K=2,Rq=20, R=Rsol),M)

edit retag close merge delete

Sort by » oldest newest most voted

You have (i) not to use the same name for the function R and the expression R(x), (ii) to make Rsol be a callable symbolic expression (i.e. replace Rsol by Rsol(x)) and (iii) to use substitute_function for replacing R by Rsol. Here is the full code:

sage: var('Rq,k,K')
(Rq, k, K)
sage: M = function('M')
sage: R = function('R')
sage: de2 = diff(R(x), x) == -K*(R(x) - Rq)
sage: de1 = diff(M(x), x) == -k*(M(x) - R(x))
sage: Rsol(x) = desolve(de2.subs(k=1,K=2,Rq=20), R(x), ics=[0,15])
sage: Rsol(x)
5*(4*e^(2*x) - 1)*e^(-2*x)
sage: de1.subs(k=1).substitute_function(R, Rsol)  # to check that the substitution works
diff(M(x), x) == 5*(4*e^(2*x) - 1)*e^(-2*x) - M(x)
sage: Msol(x) = desolve(de1.subs(k=1).substitute_function(R, Rsol), M(x))
sage: Msol(x)
(_C + 5*e^(-x) + 20*e^x)*e^(-x)


The symbol _C stands for an arbitrary constant.

more

sage: de1.subs({R: sin(x)})
diff(M(x), x) == -M(x) + sin(x)


Alternatively, you can use

sage: R = function('R')
sage: Rx = R(x)
sage: de1 = diff(M) == -k(M - Rx)
sage: de1.substitute_function(R, sin)
diff(M(x), x) == -M(x) + sin(x)

more