exercises

up

 

chapter 1 chapter 2 chapter 3

Home keywords c bibliography

 

exercises chapter 3

    Exercise 1:

Another example is the evaluation of the roots of a quadratic equation:

x2 + 2px +q = 0

One usually calculates the roots via the following formula:

x = -p ± (p2 - q)½

An alternative form is

x = -q / ( p ± (p2 - q)½ )

Well, of course both solutions are mathematically equivalent. But the second one (which looks more complicated) makes use of an additional division, compared to the first one. This additional division makes it usually less efficient, because it takes more time to evaluate. But once the difference p2 - q becomes small, it may be zero. Then the first formula results in zero, while the second one still gives an (approximate) value. Write a program which evaluates the solution (belonging to the + sign in both formulas) of the quadratic equation with constants p=1 and q=2-n with n=10...60. Make use of the function sqrtf which evaluates the square root of a float (you have to include math.h). Usually one will use the function sqrt which has a double as an argument and as the return type. But as the square root of (p2-q) is the limiting factor in these evaluation, it is interesting to compare both versions of the sqrt-function. Compare the results using sqrtf and sqrt, respectively. The output should contain one value of n per line with the respective results of both formulas, like

10    x1    x2
11    x1    x2
...
60    x1    x2

Where x1 and x2 are the results of the two formulas given above.

    Exercise 2:        Numerical differentiation

Numerical differentiation is an often needed mathematical calculation. Approximately one can use

f'(x0)=[f(x0+h)-f(x0)]/h

which in the limit h->0 (if it exists) is called the derivative of f at x0. Write a program which numerically derives the function f(x) = sin (x) at

x0 = 0

x0 = Pi / 2

Therefore decrease h from 1E-1 to 1E-20 and make an output table for the results. Again use doubles and floats for this exercise and compare the respective values and the mathematically correct one.

email me: Daniel Schürmann