Numerical differentiation

sample solution

from math import exp, cos, sin, log, pi

def fun1(x):
        return exp(x)

def fun2(x):
        return exp(-2*x*x)

def fun3(x):
        return cos(x)

def fun4(x):
        return log(x)

def numdiff(f, x, h):
        return ( (f(x+h) - f(x-h)) / (2*h) )

h = 0.01

x1 = 0
a1 = numdiff(fun1, x1, h)
e1 = a1 - exp(x1) # the derivative of e^x = e^x
print(f"f(x) = (e**x) at x={x1:.2f} is: {a1:.10f}\nerror = {e1:.10f}\n")

x2 = 1
a2 = numdiff(fun2, x2, h)
e2 = a2 - -4*exp(-2*x2*x2)*x2 # the derivative of e^(-2x^2) = -4e^(-2x^2)x
print(f"f(x) = (e**(-2x**2)) at x={x2:.2f} is: {a2:.10f}\nerror = {e2:.10f}\n")

x3 = pi/2
a3 = numdiff(fun3, x3, h)
e3 = a3 -  -sin(x3) # the derivative of cos(x) = -sin(x)
print(f"f(x) = cos(x) at x={x3:.2f} is: {a3:.10f}\nerror = {e3:.10f}\n")

x4 = 1
a4 = numdiff(fun4, x4, h)
e4 = a4 -  1/x4 # the derivative of ln(x) = 1/x
print(f"f(x) = cos(x) at x={x4:.2f} is: {a4:.10f}\nerror = {e4:.10f}\n")