Numerical differentiation
The following equation can be used to find an approximate derivative of a mathematical function f(x) if h is sufficiently small:
f'(x) \approx \frac{f(x+h)-f(x-h)}{2h}
Write a function numdiff(f, x, h)
that uses the equation above to return the approximation of the derivative of a mathematical function represented by a function f(x)
.
Your function numdiff(f, x, h)
should accept three arguments as inputs:
f
: the name of the function to be differentiatedx
: the value at which to differentiatef
h
: the value ofh
to be used in the approximation equation above
Once written, you could use your function in the following way to approximate the derivative of x^{2} at x=3.0 using h=0.01 (this example is shown using Python):
3.0, 0.01) numdiff(myfun,
where you have defined myfun
as:
def myfun(x):
return x*x
In this case numdiff(myfun, 3.0, 0.01)
should return:
1]: numdiff(myfun, 3.0, 0.01)
In [1]: 5.999999999999872 Out[
Use your function numdiff
to differentiate:
- f(x) = \left( e^{x} \right) at x=0
- f(x) = \left( e^{-2x^{2}} \right) at x=1
- f(x) = \left( \cos x \right) at x = \pi/2
- f(x) = \left( \ln x \right) at x=1
Use h = 0.01
In each case write out the true value, the value given by your function numdiff
, and the error, i.e., the difference between the true value and your approximation. Use 10 decimal places of precision.
If you need help finding out what the true exact solutions to these derivatives are, (1) try to remember your calculus!, (2) ask a classmate, (3) google it, or (4) ask me (at which point I will direct you to WolframAlpha).
Hints
- the \ln function (logarithm, base e) is typically called
log()
in programming languages like Python, MATLAB / Octave, R and C, whereas the logarithm, base 10 (typically referred to in math class as \mathrm{log}), is typically calledlog10()
in programming languages. - In Python logarithm base e is
math.log()
and logarithm base 10 ismath.log10
. You will need toimport math
to use them. The exponential function e^{x} in Python ismath.exp()
. The cosine function \cos in Python ismath.cos()
. Finally \pi in Python ismath.pi
.