5
#include "conjugate_gradient.h"
9
* Nathan Hurst <njh@njhurst.com>
10
* Tim Dwyer <tgdwyer@gmail.com>
12
* Copyright (C) 2006 Authors
14
* Released under GNU LGPL.
17
/* lifted wholely from wikipedia. Well, apart from the bug in the wikipedia version. */
22
matrix_times_vector(valarray<double> const &matrix, /* m * n */
23
valarray<double> const &vec, /* n */
24
valarray<double> &result) /* m */
26
unsigned n = vec.size();
27
unsigned m = result.size();
28
assert(m*n == matrix.size());
29
const double* mp = &matrix[0];
30
for (unsigned i = 0; i < m; i++) {
32
for (unsigned j = 0; j < n; j++)
33
res += *mp++ * vec[j];
38
static double Linfty(valarray<double> const &vec) {
39
return std::max(vec.max(), -vec.min());
43
inner(valarray<double> const &x,
44
valarray<double> const &y) {
46
for(unsigned i = 0; i < x.size(); i++)
48
return total;// (x*y).sum(); <- this is more concise, but ineff
52
conjugate_gradient(double **A,
57
unsigned max_iterations) {
58
valarray<double> vA(n*n);
59
valarray<double> vx(n);
60
valarray<double> vb(n);
61
for(unsigned i=0;i<n;i++) {
64
for(unsigned j=0;j<n;j++) {
68
conjugate_gradient(vA,vx,vb,n,tol,max_iterations);
69
for(unsigned i=0;i<n;i++) {
74
conjugate_gradient(valarray<double> const &A,
76
valarray<double> const &b,
77
unsigned n, double tol,
78
unsigned max_iterations) {
79
valarray<double> Ap(n), p(n), r(n);
80
matrix_times_vector(A,x,Ap);
82
double r_r = inner(r,r);
85
while(k < max_iterations && r_r > tol) {
92
p = r + (r_r_new/r_r)*p;
94
matrix_times_vector(A, p, Ap);
95
double alpha_k = r_r_new / inner(p, Ap);
100
printf("njh: %d iters, Linfty = %g L2 = %g\n", k,
101
std::max(-r.min(), r.max()), sqrt(r_r));
107
c-file-style:"stroustrup"
108
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
113
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=4:softtabstop=4