Computational Physics - Department of Physics

(Axel Boer) #1

92 3 Numerical differentiation and interpolation


3.6 Exercises.


3.1.We want you to compute the first derivative of


f(x) =tan−^1 (x)

forx=



2 with step lengthsh. The exact answer is 1 / 3. We want you to code the derivative
using the following two formulae


f 2 ′c(x) =
f(x+h)−f(x)
h
+O(h), (3.14)

and
f 3 ′c=fh−f−h
2 h
+O(h^2 ), (3.15)


withf±h=f(x±h).



  1. Find mathematical expressions for the total error due to loss of precision and due to the nu-
    merical approximation made. Find the step length which gives the smallest value. Perform
    the analysis with both double and single precision.

  2. Make thereafter a program which computes the first derivative using Eqs. (3.14) and (3.15)
    as function of various step lengthshand leth→ 0. Compare with the exact answer.
    Your program should contain the following elements:

    • A vector (array) which contains the step lengths. Use dynamic memory allocation.

    • Vectors for the computed derivatives of Eqs. (3.14) and (3.15) for both single and double
      precision.

    • A function which computes the derivative and contains callby value and reference (for
      C++ users only).

    • Add a function which writes the results to file.



  3. Compute thereafter


ε=log 10

(∣∣

∣∣


fcomputed′ −fexact′
fexact′

∣∣

∣∣


)

,

as function oflog 10 (h)for Eqs. (3.14) and (3.15) for both single and double precision. Plot
the results and see if you can determine empirically the behavior of the total error as
function ofh.

3.2.Modify your program from the previous exercise in order to include both Richardson’s
deferred extrapolation algorithm from Eq. (3.13) and Neville’s interpolation algorithm dis-
cussed in program4.cpp in this chapter. You will need to write a program for Richardson’s
algorithm. Discuss and comment your results.


3.3.Use the results from your program for the calculation of derivatives to make a table
of the derivatives as a function of the step lengthh. Write thereafter a program which reads
these results and performs a numerical interpolation usingLagrange’s formula from Eq. (3.9)
up to a polynomial of degree five. Compare the tabulated values with those obtained using
Lagrange’s formula. Compare also these results with those obtained using Neville’s algorithm
and comment your results.


3.4.Write your own C++ class which allows for operations on complex variables, such as
addition, subtraction, multiplication and division.


3.5.Write a C++ class which allows for treating one-dimensionalarrays for integer, real
and complex variables. Use your complex class from the previous exercise. Use this class to
perform simple vector addition and vector multiplication operations.

Free download pdf