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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

116 CHAPTER 4. GENERIC PROGRAMMING<br />

template <br />

class second derivative<br />

{<br />

public:<br />

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

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

{<br />

return ( fp(x+h) − fp(x) ) / h ;<br />

}<br />

private:<br />

T h;<br />

derivative fp;<br />

};<br />

Now we can build the f ′′ functor from f:<br />

second derivative spc scd2(para sin plus cos(1.0), 0.001);<br />

When we think about how we would implement the third, fourth or in general the n-th derivative,<br />

we realize that they would look much like the second one: calling the (n-1)-th derivative on x+h<br />

and x. We can explore this with a recursive implementation:<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 ( fp(x+h) − fp(x) ) / h ;<br />

}<br />

private:<br />

T h;<br />

prec derivative fp;<br />

};<br />

To save the compiler from infinite recursion we must stop this mutual referring when we reach<br />

the first derivative. Note that we cannot use ‘if’ or ‘?:’ to stop the recursion because both of its<br />

respective branches are evaluated and one of them still contains the infinite recursion. Recursive<br />

template definitions are terminated with a specialization like this:<br />

template <br />

class nth derivative<br />

{<br />

public:<br />

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

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

{<br />

return ( f(x+h) − f(x) ) / h ;<br />

}<br />

private:

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

Saved successfully!

Ooh no, something went wrong!