Search code examples
python-3.xfunctionsympysymbols

How can i subs or replace a sympy function to a sympy symbol


Im trying to replace the sympy function x(t) to the sympy symbol x.

It should be like something like this:

Before the replace: funcion0=t**2*sp.cos((x(t)/2))

After the replace: funcion1=t**2*sp.cos((x/2))

import sympy as sp
t = sp.Symbol('t')
x = sp.Function('x')
funcion=t**2*sp.cos((x(t)/2))

def replace(funcion):
   funcion1=funcion.subs(x(t), x)
   return funcion1

I know that doesnt work, but maybe it helps to understand what im saying hahaha. Thanks!!!!


Solution

  • When working with SymPy, it's best to keep in mind the differences between functions, symbols and physical numbers like floats or ints. Here, you want the function x (evaluated at t) to be substituted with the symbol x. If you are uncertain at any point, it is best to add what the type of the variable to its name as I have done below:

    import sympy as sp
    t, x_sym = sp.symbols('t x')
    x_func = sp.Function('x')
    function = t**2*sp.cos((x_func(t)/2))
    
    def replace(funcion):
        function1 = funcion.subs(x_func(t), x_sym)
        return function1
    
    print(replace(function))
    

    It should give you the desired result.