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) )
= 0.01
h
= 0
x1 = numdiff(fun1, x1, h)
a1 = a1 - exp(x1) # the derivative of e^x = e^x
e1 print(f"f(x) = (e**x) at x={x1:.2f} is: {a1:.10f}\nerror = {e1:.10f}\n")
= 1
x2 = numdiff(fun2, x2, h)
a2 = a2 - -4*exp(-2*x2*x2)*x2 # the derivative of e^(-2x^2) = -4e^(-2x^2)x
e2 print(f"f(x) = (e**(-2x**2)) at x={x2:.2f} is: {a2:.10f}\nerror = {e2:.10f}\n")
= pi/2
x3 = numdiff(fun3, x3, h)
a3 = a3 - -sin(x3) # the derivative of cos(x) = -sin(x)
e3 print(f"f(x) = cos(x) at x={x3:.2f} is: {a3:.10f}\nerror = {e3:.10f}\n")
= 1
x4 = numdiff(fun4, x4, h)
a4 = a4 - 1/x4 # the derivative of ln(x) = 1/x
e4 print(f"f(x) = cos(x) at x={x4:.2f} is: {a4:.10f}\nerror = {e4:.10f}\n")
Numerical differentiation
sample solution