H.W.6

# dsin(x)/dx
import math as m
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2
# two point formula
def df_dx_forward(f, x, h):
return (f(x+h)-f(x))/h
def df_dx_backward(f, x, h):
return (f(x)-f(x-h))/h
# three point formula
def df_dx_tp(f, x, h):
return (f(x+h)-f(x-h))/(2*h)
if __name__=="__main__":
x=np.linspace(-2, 2, 1000)
dydx_f=np.zeros_like(x, float)
dydx_b=np.zeros_like(x, float)
dydx_t=np.zeros_like(x, float)
h=1e-6
i=0
for xx in x:
dydx_f[i]=df_dx_forward(f, xx, h)
dydx_b[i]=df_dx_backward(f, xx, h)
dydx_t[i]=df_dx_tp(f, xx, h)
i+=1
plt.subplot(3, 1, 1)
plt.plot(x, dydx_f, "r-")
plt.title("Two_Point(Forward)")
plt.subplot(3, 1, 2)
plt.plot(x, dydx_b, "b-")
plt.title("Two_Point(Backward)")
plt.subplot(3, 1, 3)
plt.plot(x, dydx_t, "g-")
plt.title("Three-Point")
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.2, hspace=0.4)
plt.show()