Search code examples
pythonsympy

How to make Derivative(f(x), x) take an explicit value after f is defined?


So I need to make take some derivatives first and later in the code (when the explicit form of f(x) is given) substitute the Derivative(f(x), x) with the explicit form of the derivative

import sympy as sp

import math 

x = sp.symbols('x')

f = sp.Function('f')('x')

df = f.diff(x)    
   
f = sp.sin(x)

print(df)

What I expect to see as an output is cos(x) and not Derivative(f(x), x) that it gives me anyway. I tried subs and doit with no success. What would be a proper way of getting what I need?


Solution

  • Substitute your known function into the derivative and execute the doit method:

    import sympy as sp
    import math 
    
    x = sp.symbols('x')
    f = sp.Function('f')('x')
    df = f.diff(x)    
    f_known = sp.sin(x)
    
    df.subs(f, f_known).doit()