H.W.7

# Find second order derivative HW7
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2
def d2f_dx2(f, x, h): # from Taylor expansion
return (f(x+h)+f(x-h)-2*f(x))/h**2
if __name__=='__main__':
x=np.linspace(-2, 2, 1000)
_d2f_dx2=np.zeros_like(x, float)
for i in range(len(x)):
_d2f_dx2[i]=d2f_dx2(f, x[i], 1e-6)
plt.plot(x, _d2f_dx2, 'ro', ms=2)
plt.ylim([1.5, 2.5])
plt.title(r"$\frac{d^2}{dx^2} x^2$")
plt.show()
미분 여러번 할 경우
import numpy as np
def f(x):
return x**3+x**2+x
def df_dx(f, x, h, n=1):
if(n==1):
return (f(x+h)-f(x-h))/(2*h)
else:
return df_dx(f, x, h, n-1)