Please look at my code and help me. I'm writing a code the approximates the Derivative of a function. To visually check how close my approximation is with the real derivative, I'm plotting both of them together.
My problem is when the function is not defined at zero, like 1/x with a derivative of '1/x^2.
Thanks in advance.
# -*- coding: utf-8 -*-
from pylab import *
import math
def Derivative(f,x, Tol = 10e-5, Max = 20):
try:
k = 2
D_old = (f(x+2.0**(-k))-f(x-2.0**-k))/(2.0**(1-k))
k = 3
D_new = (f(x+2.0**(-k))-f(x-2.0**-k))/(2.0**(1-k))
E_old = abs(D_new - D_old)
while True:
D_old = D_new
k+=1
D_new = (f(x+2.0**(-k))-f(x-2.0**-k))/(2.0**(1-k))
E_new = abs(D_old - D_new)
if E_new < Tol or E_new >= E_old or k >= Max:
return D_old
except:
return nan
def Fa(x):
return math.sin(2*math.pi*x)
def Fap(x):
return 2*math.pi*math.cos(2*math.pi*x)
def Fb(x):
return x**2
def Fbp(x):
return 2*x
def Fc(x):
return 1.0/x
def Fcp(x):
if abs(x)<0.01:
return 0
else:
return -1.0/x**2
def Fd(x):
return abs(x)
def Fdp(x):
return 1 #since it's x/sqrt(x**2)
# Plot of Derivative Fa
xx = arange(-1, 1, 0.01) # A Numpy vector of x-values
yy = [Derivative(Fa, x) for x in xx] # Vector of f’ approximations
plot(xx, yy, 'r--', linewidth = 5) # solid red line of width 5
yy2 = [Fap(x) for x in xx]
plot(xx, yy2, 'b--', linewidth = 2) # solid blue line of width 2
# Plot of Derivative Fb
yy = [Derivative(Fb, x) for x in xx] # Vector of f’ approximations
plot(xx, yy, 'g^', linewidth = 5) # solid green line of width 5
yy2 = [Fbp(x) for x in xx]
plot(xx, yy2, 'y^', linewidth = 2) # solid yellow line of width 2