pythonsympyderivativecalculus

Create a function, that is the derivative of a function


I have in my code a function, let's say:

def test_func(x):
    return(3*x**2)

I want my code to calculate the derivative der_test_func of test_func, so that der_test_func is a function, too. Means, I should be able to do

>>> print(der_test_func(5))
>>> 30

Or I should be able to put it inside another function so that it gets handled reasonably, e.g.

def func2(x):
    y = 10*der_test_func(x)
    return(y)

>>> print(func2(5))
>>> 300

I found out that sympy does derivations, which looks at first sight great, but it returns expressions, whereas I want somehow to have a function, so that I give input to it and get output. Any suggestions or workarounds on how to create der_test_func? Tnx


Solution

  • If you pass a SymPy Symbol into your function then it will be converted to a symbolic expression. You can then differentiate that and make a function to call it:

    In [11]: def test_func(x):
        ...:     return 3*x**2
        ...: 
    
    In [12]: x = sympy.symbols('x')
    
    In [13]: f = test_func(x)
    
    In [14]: f
    Out[14]: 
       2
    3⋅x 
    
    In [15]: f.diff(x)
    Out[15]: 6⋅x
    
    In [16]: g = sympy.Lambda(x, f.diff(x))
    
    In [17]: g
    Out[17]: x ↦ 6⋅x
    
    In [18]: g(5)
    Out[18]: 30
    

    This will work for a simple function like the example given but won't work if your function does more complicated things like using if/else or loops etc.