Search code examples
pythonnumpysympyderivative

Derivative using Numpy or Other Library for lambda sin function


So i have this newton optimation problem where i must found the value f'(x) and f''(x) where x = 2.5 and the f = 2 * sin(x) - ((x)**2/10) for calculating, but i tried using sympy and np.diff for the First and Second Derivative but no clue, cause it keep getting error so i go back using manual derivate, Any clue how to derivative the function f with help of other library, Here's the code

def Newton(x0):
  x = x0
  f = lambda x : 2 * np.sin (x) - ((x)**2/10)
  f_x0 = f(x0)
  #First Derivative
  f1 = lambda x : 2 * np.cos (x) - ((x)/5)
  f_x1 = f1(x0)
  #Second Derivative
  f2 = lambda x : -2 * np.sin (x) - (1/5)
  f_x2 = f2(x0)


  x1 = x0 - (f_x1/f_x2)
  x0 = x1

  return x,f_x0,f_x1,f_x2,x0

finding first and second derivative without the manual way.


Solution

  • In your case, the derivates can be calculated using the scipy library as follows:

    from scipy.misc import derivative
    
    def f(x):
        return 2 * sin(x) - ((x)**2/10)
    
    print("First derivative:" , derivative(f, 2.5, dx=1e-9))
    print("Second derivative", derivative(f, 2.5, n=2, dx=0.02))
    

    Here the first and second derivative is calculated for your function at x=2.5.

    The same can be done with the sympy library and some may find this easier than the above method.

    from sympy import *
    
    x = Symbol('x')
    y = 2 * sin(x) - ((x)**2/10) #function
    yprime = y.diff(x) #first derivative function
    ydoubleprime = y.diff(x,2) #second derivative function
    
    f_first_derivative = lambdify(x, yprime)
    f_second_derivative = lambdify(x, ydoubleprime)
    
    print("First derivative:" , f_first_derivative(2.5))
    print("Second derivative",f_second_derivative(2.5))