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.

12 CHAPTER 1. GOOD AND BAD SCIENTIFIC SOFTWARE<br />

Programmers trans<strong>for</strong>m this mathematical notation into a <strong>for</strong>m that a compiler understands,<br />

by using operations from the language. The result could look like Listing 1.1. Do not read it<br />

in detail, just skim it.<br />

#include <br />

#include <br />

double one norm(int size, double ∗vp)<br />

{<br />

int i;<br />

double sum= 0;<br />

<strong>for</strong> (i= 0; i < size; i++)<br />

sum+= fabs(vp[i]);<br />

return sum;<br />

}<br />

double dot(int size, double ∗vp, double ∗wp)<br />

{<br />

int i;<br />

double sum= 0;<br />

<strong>for</strong> (inti= 0; i < size; i++)<br />

sum+= vp[i] ∗ wp[i];<br />

return sum;<br />

}<br />

int cg(int size, int nnz, int∗ aip, int∗ ajp, double∗ avp,<br />

double ∗x, double ∗b, void (∗lpre)(int, double∗, double∗), double eps)<br />

{<br />

int i, j, iter= 0;<br />

double rho, rho 1, alpha;<br />

double ∗p= (double∗) malloc(size ∗ sizeof(double));<br />

double ∗q= (double∗) malloc(size ∗ sizeof(double));<br />

double ∗r= (double∗) malloc(size ∗ sizeof(double));<br />

double ∗z= (double∗) malloc(size ∗ sizeof(double));<br />

// r= b;<br />

<strong>for</strong> (i= 0; i < size; i++)<br />

r[i]= b[i];<br />

// r−= A∗x;<br />

<strong>for</strong> (i= 0; i < nnz; i++)<br />

r[aip[i]]−= avp[i] ∗ b[ajp[i]];<br />

while (one norm(size, r) >= eps) {<br />

// z = solve(L, r);<br />

(∗lpre)(size, z, r); // function pointer call<br />

rho= dot(size, r, z);<br />

if (!iter) {<br />

<strong>for</strong> (i= 0; i < size; i++)<br />

p[i]= z[i];<br />

} else {<br />

<strong>for</strong> (i= 0; i < size; i++)<br />

p[i]= z[i] + rho / rho 1 ∗ p[i];

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

Saved successfully!

Ooh no, something went wrong!