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 119<br />

std::cout ≪ ”Seventh derivative of sin 1 at x=3 is ”<br />

≪ make nth derivative(sin 1, 0.00001)(3.0) ≪ ’\n’;<br />

In the cases above the type of the functor was obvious because we wrote the class ourselves. The<br />

type is less obvious if the type is constructed from an expression, <strong>for</strong> instance by a λ-function.<br />

Support <strong>for</strong> λ-functions will be introduced with C ++0x. 25 Emulation is available since some<br />

years with Boost.Lambda [?]. For instance, we can generate a functor object that computes<br />

with the following short expression:<br />

(3.5 ∗ 1 + 4.0) ∗ 1 ∗ 1;<br />

p(x) = 3.5x 3 + 4x 2 = (3.5x + 4)x 2<br />

This expression can be used with our derivative function:<br />

make nth derivative((3.5 ∗ 1 + 4.0) ∗ 1 ∗ 1, 0.0001)<br />

to generate a functor computing (approximating) 21x + 8.<br />

With the lambda expressions, we do not even know the type of our functor but we can compute<br />

its derivative. The type is in fact so long 26 that it is much easier to implement our own functor<br />

when we were obliged to spell the type out.<br />

The following listing illustrates how to approximate p ′′ (2):<br />

#include <br />

// .. our definitions of derivatives<br />

int main()<br />

{<br />

using boost::lambda:: 1;<br />

std::cout ≪ ”Second derivative of 3.5∗xˆ3+4∗xˆ2 at x=2 is ”<br />

≪ make nth derivative((3.5 ∗ 1 + 4.0) ∗ 1 ∗ 1, 0.0001)(2) ≪ ’\n’;<br />

return 0;<br />

}<br />

Un<strong>for</strong>tunately, we cannot keep the results of our computations if we do not know their types<br />

with current standard C ++. In C ++0x, we will be able to let the compiler deduce the type:<br />

auto p= (3.5 ∗ 1 + 4.0) ∗ 1 ∗ 1; // With <strong>C++</strong>0x<br />

auto p2= make nth derivative(p, 0.0001);<br />

Once defined, we can reuse p and p2 as often as we want. Of course, calculating the derivatives<br />

of polynomials can be done better than with differential quotients. We will discuss this in<br />

Section 8.2.<br />

25 TODO: Try in g++ 4.3 and 4.4?<br />

26 boost::lambda::lambda functor

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

Saved successfully!

Ooh no, something went wrong!