In [1]:
import numpy as np
import matplotlib.pyplot as plt
In [2]:
def f(x):
    return np.sin(x)

def df(x):
    return np.cos(x)
In [3]:
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
In [7]:
%matplotlib inline
plt.loglog(hs[:50], errs[:50])
plt.xlabel(r'$h$', fontsize=20)
plt.ylabel('relative error')
Out[7]:
<matplotlib.text.Text at 0x11447d3c8>
In [8]:
f(x + 1e-8)
Out[8]:
0.84147099021091942
In [9]:
f(x)
Out[9]:
0.8414709848078965
In [10]:
f(x + 1e-8) - f(x)
Out[10]:
5.4030229179602429e-09
In [11]:
(f(x + 1e-8) - f(x))/1e-8
Out[11]:
0.54030229179602429
In [ ]: