import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.sin(x)
def df(x):
return np.cos(x)
h = 0.25
x = 1.0
hs = []
errs = []
dfexact = df(x)
while h > 0:
dfapprox = (f(x+h) - f(x)) / h
hs.append(h)
errs.append(abs(dfexact - dfapprox)/dfexact)
h /= 2.0
%matplotlib inline
plt.loglog(hs[:50], errs[:50])
plt.xlabel(r'$h$', fontsize=20)
plt.ylabel('relative error')
f(x + 1e-8)
f(x)
f(x + 1e-8) - f(x)
(f(x + 1e-8) - f(x))/1e-8