Search code examples
pythonscipyderivative

finding the derivative of function using scipy.misc.derivative


I'm having a problem that the function and its derivative should have the same value. The function is y=e^x so its derivative should be the same y'=e^x but when i do it with scipy :

from scipy.misc import derivative
from math import *

def f(x):
    return exp(x)

def df(x):
    return derivative(f,x)

print(f(1))
print(df(1))

it will print the different value f(1) = 2.178... df(1) = 3.194... so it means, e has the different value. Can anyone explain that and how to fix it?


Solution

  • As pointed out by @SevC_10 in his answer, you are missing dx parameter.

    I like to show case the use of sympy for derivation operations, I find it much easier in many cases.

    import sympy
    import numpy as np
    
    x = sympy.Symbol('x')
    
    f = sympy.exp(x) # my function e^x
    df = f.diff() # y' of the function = e^x
    
    f_lambda = sympy.lambdify(x, f, 'numpy')
    df_lambda = sympy.lambdify(x, yprime, 'numpy') # use lambdify
    
    print(f_lambda(np.ones(5)))
    
    # array([2.71828183, 2.71828183, 2.71828183, 2.71828183, 2.71828183])
    
    print(df_lambda(np.ones(5)))
    
    # array([2.71828183, 2.71828183, 2.71828183, 2.71828183, 2.71828183])
    
    print(f_lambda(np.zeros(5)))
    
    # array([1., 1., 1., 1., 1.])
    
    print(df_lambda(np.zeros(5)))
    
    # array([1., 1., 1., 1., 1.])
    
    
    print(f_lambda(np.array([0, 1, 2, 3, 4])))
    # array([ 1.        ,  2.71828183,  7.3890561 , 20.08553692, 54.59815003])
    
    print(df_lambda(np.array([0, 1, 2, 3, 4])))
    # array([ 1.        ,  2.71828183,  7.3890561 , 20.08553692, 54.59815003])