41 valarray<double>
const &vec,
44 unsigned n = vec.size();
45 unsigned m =
result.size();
46 COLA_ASSERT(m*n == matrix.size());
54 double const *mp = &
const_cast<valarray<double> &
>(matrix)[0];
56 const double* mp = &matrix[0];
58 for (
unsigned i = 0; i < m; i++) {
60 for (
unsigned j = 0; j < n; j++)
61 res += *mp++ * vec[j];
74 valarray<double>
const &y) {
76 for(
unsigned i = 0; i < x.size(); i++)
82 valarray<double>
const &b,
83 valarray<double>
const &x,
86 double cost = 2. *
inner(b,x);
87 valarray<double> Ax(n);
88 for (
unsigned i=0; i<n; i++) {
90 for (
unsigned j=0; j<n; j++) {
91 Ax[i] += A[i*n+j]*x[j];
94 return cost -
inner(x,Ax);
99 valarray<double>
const &b,
100 unsigned const n,
double const tol,
101 unsigned const max_iterations) {
103 valarray<double> Ap(n), p(n), r(n);
106 double r_r =
inner(r,r);
108 double tol_squared = tol*tol;
112 while(k < max_iterations && r_r > tol_squared) {
114 double r_r_new = r_r;
118 r_r_new =
inner(r,r);
119 if(r_r_new<tol_squared)
break;
120 p = r + (r_r_new/r_r)*p;
123 double alpha_k = r_r_new /
inner(p, Ap);
127 printf(
" CG[%d] %.15f %.15f\n",k,previousCost,cost);
void conjugate_gradient(valarray< double > const &A, valarray< double > &x, valarray< double > const &b, unsigned const n, double const tol, unsigned const max_iterations)
double compute_cost(valarray< double > const &A, valarray< double > const &b, valarray< double > const &x, const unsigned n)
double inner(valarray< double > const &x, valarray< double > const &y)
static void matrix_times_vector(valarray< double > const &matrix, valarray< double > const &vec, valarray< double > &result)