/* * Simple implementation of Conjugate Gradient algorithm for an * arbitrary symmetric positive definite square matrix. * Instead of assuming positive-definite-ness, * we assume that in every division, the denominator is non-0. * Based on https://en.wikipedia.org/wiki/Conjugate_gradient_method */ #include $input int N = 5; // should be greater than 0 $input double A[N][N]; // only use upper triangle $input double B[N]; // right-hand side void cg(int n, double a[n][n], double b[n], double x[n], int nsteps) { double r[n]; double p[n]; double temp[n]; double tempp[n]; double rsold; double rsnew; double rsfrac; double alpha; // x = 0 [could make this arbitrary] for (int i=0; i rsold = 0.0; for (int i=0; i rsnew = 0.0; for (int i=0; i