Search code examples
pythonsympysymbolic-math

How to use SymPy to substitute a pattern


In my code I need to substitute ALL the expressions of sin(g(t)) (g being a continuous function) to g(t) (it's the tight angle approximation). This is a sample of what I get from my code:

-29.4*sin(2*t) - 19.6*sin(f(t)) + 4.0*Derivative(f(t), t)**2

I need to substitute both sin(f(t)) and sin(2*t). Not just one of them and sin(2*t) changes, (sin(f(t)) is always the same). Is there a simpler way than adding an extra variable for what's inside the sin or isn't there?


Solution

  • Is this what you are trying to do?

    import sympy as sp
    
    t = sp.symbols('t')
    f = sp.Function('f')
    
    expr_v1 = -29.4*sp.sin(2*t) - 19.6*sp.sin(f(t)) + 4.0*sp.Derivative(f(t), t)**2
    print('expr_v1 = ', expr_v1)
    
    expr_v2 = expr_v1.replace(sp.sin, lambda *args: args[0])
    print('expr_v2 = ', expr_v2)
    
    expr_v1 =  -29.4*sin(2*t) - 19.6*sin(f(t)) + 4.0*Derivative(f(t),t)**2
    expr_v2 =  -58.8*t - 19.6*f(t) + 4.0*Derivative(f(t), t)**2