# Substitute expression for function in differential equation

This is related to 8293, but a lot has changed since then, so I wonder if there is a way to achieve this now. Expanding on an example from 26114, I define a differential equation based on unevaluated functions and then want to substitute one of the functions (H) by an expression (T_s^2):

sage: var('T_s')
sage: B = function('B')(T_s)
sage: E = function('E')(T_s)
sage: H = function('H')(T_s)
sage: eq_B_TS = B == H/E
sage: eq1 = diff(eq_B_TS, T_s)
sage: eq1
diff(B(T_s), T_s) == -H(T_s)*diff(E(T_s), T_s)/E(T_s)^2 + diff(H(T_s), T_s)/E(T_s)
sage: eq1.subs(H == T_s^2)
diff(B(T_s), T_s) == -T_s^2*diff(E(T_s), T_s)/E(T_s)^2 + diff(H(T_s), T_s)/E(T_s)


I expected this output:

diff(B(T_s), T_s) == -T_s^2*diff(E(T_s), T_s)/E(T_s)^2 + 2*T_s/E(T_s)


However, the substitution was not carried out inside the differential. Is this a missing feature or a bug? Basically, I would like to be able to formulate general symbolic equations including differentials and integrals, and then insert explicit expressions for the different elements that would allow evaluation of the differentials and integrals.

edit retag close merge delete

Sort by » oldest newest most voted

Do not use the same identifier for a symbolic function and the symbolic expression resulting from the evaluation of this function at T_s, e.g. write BT = function('B')(T_s) instead of B = function('B')(T_s). Then define a callable symbolic expression for the explicit form you want to substitute, e.g. H0(T_s) = T_s^2. Finally use substitute_function instead of subs. Here is the full code:

sage: var('T_s')
T_s
sage: BT = function('B')(T_s)
sage: ET = function('E')(T_s)
sage: HT = function('H')(T_s)
sage: eq_B_TS = BT == HT/ET
sage: eq1 = diff(eq_B_TS, T_s)
sage: eq1
diff(B(T_s), T_s) == -H(T_s)*diff(E(T_s), T_s)/E(T_s)^2 + diff(H(T_s), T_s)/E(T_s)
sage: H0(T_s) = T_s^2
sage: eq1.substitute_function(H, H0)
diff(B(T_s), T_s) == -T_s^2*diff(E(T_s), T_s)/E(T_s)^2 + 2*T_s/E(T_s)

more

Wow, this is interesting, thank you! Why is it that substitute_function() gives different results depending on whether I substitute H0 (callable expression) or an expression? It actually gives the wrong result if I substitute an expression. In the below, I would expect the last two lines to give the same result, but they don't.

sage: var('T_s', 'x')
sage: BT = function('B')(T_s)
sage: ET = function('E')(T_s)
sage: HT = function('H')(T_s)
sage: eq_B_TS = BT == HT/ET + T_s/x
sage: eq_B_TS.show()
sage: eq1 = diff(eq_B_TS, T_s)
sage: eq1.show()
sage: H0(T_s) = x^2
sage: eq1.substitute_function(H, H0).show()
sage: eq1.substitute_function(H, H0(T_s)).show()
sage: eq1.substitute_function(H, x^2).show()


OK, I think this is a bug, substitute_function() with a non-callable expression should raise an error. I will add this to Ticket 17757