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.

4.8. FUNCTORS 111<br />

vector x(3), y(4);<br />

v= w;<br />

x= y;<br />

The last two lines are incompatible vector assignments. The difference is that the imcompatibility<br />

in the second assignment x= y; is discovered at run time in our assertion. The assignment<br />

v= w; does not even compile because fixed-size vectors of dimension 3 only accept vectors of the<br />

same dimension as argument.<br />

Like type arguments, non-type template arguments can have defaults. Say the most frequent<br />

dimension of our vectors is three because we live in a three-dimensional world, relativity and<br />

string theory aside. Then we save some typing with a default:<br />

template <br />

class fsize vector<br />

{ /∗ ... ∗/ };<br />

fsize vector v, w, x, y;<br />

fsize vector space time;<br />

fsize vector string;<br />

4.8 Functors<br />

Let us develop a mathematical algorithm <strong>for</strong> computing the finite difference of a differentiable<br />

function f. The finite difference is an approximation of the first derivative by<br />

f ′ (x) ≈<br />

where h is a small value also called spacing.<br />

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

h<br />

A general function <strong>for</strong> computing the finite difference is presented here:<br />

#include <br />

#include <br />

// Function taking a function argument<br />

double finite difference( double f( double ), double x, double h ) {<br />

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

}<br />

double sin plus cos( double x ) {<br />

return sin(x) + cos(x) ;<br />

}<br />

int main() {<br />

std::cout ≪ finite difference( sin plus cos, 1., 0.001 ) ≪ std::endl ;<br />

std::cout ≪ finite difference( sin plus cos, 0., 0.001 ) ≪ std::endl ;<br />

}

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

Saved successfully!

Ooh no, something went wrong!