pythonsympysymbolic-mathderivative

Symbolic derivative with sympy of a symbolic function


If I define a variable e.g. $ V = f(r) * x^2 $ and I choose $f(r)$ as a symbolic function with $ r = \sqrt(x^2+y^2+z^2) $. Now I take the derivative of V with respect to x and want to get the solution from sympy, then the result is:

x**3*Subs(Derivative(f_A(_xi_1), _xi_1), _xi_1, sqrt(x**2 + y**2 + z**2))/sqrt(x**2 + y**2 + z**2) + 2*x*f_A(sqrt(x**2 + y**2 + z**2))

Its possible to get a symbolic output for the derivative like $ \frac{x^3}{r} df(r)/dx + 2x f(r) $

import sympy as sp

x, y, z = sp.symbols('x y z')
r = sp.sqrt(x**2 + y**2 + z**2)  
f_A = sp.Function('f_A')(r)  

V = f_A * x**2  

dV_dx = sp.diff(V, x)

print(dV_dx)

Solution

  • I would create r as a function of x, y, z:

    import sympy as sp
    
    x, y, z = sp.symbols('x y z')
    r = sp.Function("r")(x, y, z)
    r_expr = sp.sqrt(x**2 + y**2 + z**2)
    f_A = sp.Function('f_A')(r)  
    
    V = f_A * x**2  
    V
    # x**2*f_A(r(x, y, z))
    

    The differentiation produces:

    V.diff(x)
    # x**2*Derivative(f_A(r(x, y, z)), r(x, y, z))*Derivative(r(x, y, z), x) + 2*x*f_A(r(x, y, z))
    

    You can then substitute the appropriate terms, like this:

    V.diff(x).subs(r.diff(x), r_expr.diff(x))
    # x**3*Derivative(f_A(r(x, y, z)), r(x, y, z))/sqrt(x**2 + y**2 + z**2) + 2*x*f_A(r(x, y, z))