Search code examples
sympydifferential-equations

Substitute a constant in a differential equation of second order


I managed to calculate constants but I don't know how to swap the constant in C1. Can anyone help please? :)

import sympy as sym
x, g, K, m, t = sym.symbols('x, g, K, m, t', positive=True, real=True)
dxx = sym.Eq(x(t).diff(t, 2), g - K/m*x(t).diff(t))
rešitev = sym.dsolve(dxx) 
y_res = rešitev.args[1] 
C2_enačba = sym.Eq(sym.diff(y_res.subs(x, 0), t), 0)
C2 = sym.solve(C2_enačba, 'C2')
display(C2)
C1_subs = y_res.subs(x, 0)
C1_enačba = sym.Eq(C1_subs, 0)
C1 = sym.solve(C1_enačba, 'C1') 
display(C1)

Solution

  • Substitution can be done with subs:

    rešitev.subs({sym.Symbol('C1'): C1[0], sym.Symbol('C2'): C2[0]})
    

    However, the process by which you found the constants was incorrect; you can see that the "constants" contain the variable t. This is because of a mixup of x and t in the formulas. Here is the corrected version:

    import sympy as sym
    x, g, K, m, t = sym.symbols('x, g, K, m, t', positive=True, real=True)
    dxx = sym.Eq(x(t).diff(t, 2), g - K/m*x(t).diff(t))
    rešitev = sym.dsolve(dxx) 
    y_res = rešitev.args[1] 
    C2_enačba = sym.Eq(sym.diff(y_res, t).subs(t, 0), 0)   # derivative at 0 is 0
    C2 = sym.solve(C2_enačba, 'C2')
    C1_subs = y_res.subs(t, 0)                           
    C1_enačba = sym.Eq(C1_subs, 0)                         # the value at 0 is 0
    C1 = sym.solve(C1_enačba, 'C1') 
    answer = rešitev.subs({sym.Symbol('C1'): C1[0], sym.Symbol('C2'): C2[0]})
    

    The answer is

    Eq(x(t), g*m*t/K - g*m**2/K**2 + g*m**2*exp(-K*t/m)/K**2)
    

    But your code could be much simpler if you use the current master branch of SymPy from GitHub, in which the initial and boundary conditions in dsolve are implemented.

    import sympy as sym
    x, g, K, m, t = sym.symbols('x, g, K, m, t', positive=True, real=True)
    dxx = sym.Eq(x(t).diff(t, 2), g - K/m*x(t).diff(t))
    ics = {x(0): 0, x(t).diff(t).subs(t, 0): 0}
    answer = sym.dsolve(dxx, ics=ics)
    

    The answer is same as above,

    Eq(x(t), g*m*t/K - g*m**2/K**2 + g*m**2*exp(-K*t/m)/K**2)