#!/usr/bin/env python
# coding: utf-8

# In[1]:


#centered finite difference for estimating a first derivative
def fdc(f, x, h):
    return ((f(x+h) - f(x-h)) / (2*h))


# In[2]:


from numpy import sqrt
f = lambda x: sqrt(x)


# In[3]:


fdc(f, 1, 0.1)


# In[4]:


#centered finite difference for estimating a second derivative
def fdc2(f, x, h):
    return ((f(x+h) + f(x-h) - 2*f(x)) / (h**2))


# In[5]:


fdc2(f, 1, 0.1)


# In[22]:


#Richardson exatrpolation for estimating a first derivative using centered finite differences
def richardson(f, x, h0, jmax):
    from numpy import array, zeros
    A = zeros((jmax+1, jmax+1))
    for i in range(jmax+1):
        h = h0 / (2**i)
        A[i, 0] = fdc(f, x, h)
        for j in range(1, i+1):
            A[i-j, j] = ((4**j) * A[i-j+1, j-1] - A[i-j, j-1]) / (4**j - 1) 
    print(A)
    return A[0, jmax]
    


# In[23]:


d = richardson(f, 1, 0.4, 3)


# In[21]:


d - 0.5


# In[ ]:




