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
JavaScript
x
17
17
1
def Newton(x0):
2
x = x0
3
f = lambda x : 2 * np.sin (x) - ((x)**2/10)
4
f_x0 = f(x0)
5
#First Derivative
6
f1 = lambda x : 2 * np.cos (x) - ((x)/5)
7
f_x1 = f1(x0)
8
#Second Derivative
9
f2 = lambda x : -2 * np.sin (x) - (1/5)
10
f_x2 = f2(x0)
11
12
13
x1 = x0 - (f_x1/f_x2)
14
x0 = x1
15
16
return x,f_x0,f_x1,f_x2,x0
17
finding first and second derivative without the manual way.
Advertisement
Answer
In your case, the derivates can be calculated using the scipy library as follows:
JavaScript
1
8
1
from scipy.misc import derivative
2
3
def f(x):
4
return 2 * sin(x) - ((x)**2/10)
5
6
print("First derivative:" , derivative(f, 2.5, dx=1e-9))
7
print("Second derivative", derivative(f, 2.5, n=2, dx=0.02))
8
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.
JavaScript
1
13
13
1
from sympy import *
2
3
x = Symbol('x')
4
y = 2 * sin(x) - ((x)**2/10) #function
5
yprime = y.diff(x) #first derivative function
6
ydoubleprime = y.diff(x,2) #second derivative function
7
8
f_first_derivative = lambdify(x, yprime)
9
f_second_derivative = lambdify(x, ydoubleprime)
10
11
print("First derivative:" , f_first_derivative(2.5))
12
print("Second derivative",f_second_derivative(2.5))
13