03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

4.8. FUNCTORS 117<br />

};<br />

const F& f;<br />

T h;<br />

This specialization is identical with the class derivative that we now could throw away. If we keep<br />

it, we can at least reuse its functionality and variables to reduce redundancy. This is achieved<br />

by derivation (more in Chapter 6).<br />

template <br />

class nth derivative<br />

: public derivative<br />

{<br />

public:<br />

nth derivative(const F& f, const T& h) : derivative(f, h) {}<br />

};<br />

With our recursive definition we can easily define the twenty-second derivative:<br />

nth derivative spc 22(para sin plus cos(1.0), 0.00001);<br />

The new object spc 22 is again a unary functor. Un<strong>for</strong>tunately, it approximates so badly that<br />

we are too ashamed to present the results here. From Taylor series we know that the error of<br />

the f ′′ approximation is reduced from O(h) to O(h 2 ) when a backward difference is applied<br />

on the <strong>for</strong>ward difference. This said, maybe we can improve our approximation if we alternate<br />

between <strong>for</strong>ward and backward differences:<br />

template <br />

class nth derivative<br />

{<br />

typedef nth derivative prec derivative;<br />

public:<br />

nth derivative(const F& f, const T& h) : h(h), fp(f, h) {}<br />

T operator()(const T& x) const<br />

{<br />

return N & 1 ? ( fp(x+h) − fp(x) ) / h<br />

: ( fp(x) − fp(x−h) ) / h ;<br />

}<br />

private:<br />

T h;<br />

prec derivative fp;<br />

};<br />

Sadly, our 22nd derivative is still as wrong as be<strong>for</strong>e, well slightly worse. Which is particularly<br />

frustrating when we become aware that we evaluate f over four million times. 24 Decreasing h<br />

does not help either: the tangent approaches better the derivative but on the other hand the<br />

values of f(x) and f(x ± h) become quite close and their difference has only few meaningful<br />

bits. At least the second derivative improved by our alternating difference scheme as the Taylor<br />

series teach us. Another consolidating fact is that we probably did not pay <strong>for</strong> the alteration.<br />

The template argument N is known at compile time and the condition N&1 whether the last<br />

bit is on can be also evaluated during compilation. When N is odd than the operator reduces<br />

effectively to:<br />

24 TODO: Is there an efficient and well-approximating recursive scheme to compute higher order derivatives?

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!