# coding: utf-8
# # Using Richardson Extrapolation with Finite Differences
# In[1]:
from math import sin, cos
# Here are a function and its derivative. We also choose a "center" about which we carry out our experiments:
# In[ ]:
f = sin
df = cos
x = 2.3
# We then compare the accuracy of:
#
# * First-order (right) differences
# * Second-order (centered) differences
# * An estimate based on these two using Richardson extrapolation
#
# against `true`, the actual derivative
# In[19]:
for k in range(3, 10):
h = 2**(-k)
fd1 = (f(x+2*h) - f(x))/(2*h)
fd2 = (f(x+h) - f(x))/h
richardson = (-1)*fd1 + 2*fd2
true = df(x)
print "Err FD1: %g\tErr FD2: %g\tErr Rich: %g" % (
abs(true-fd1),
abs(true-fd2),
abs(true-richardson))