public static int newton (Func <vector, vector> f, ref vector x, double eps = 1e-3, double dx = 1e-7) { vector fx = f(x), z, fz; int nsteps = 0; while (++nsteps < 999) { matrix J = jacobian(f, x, fx); qrdecomposition qrJ = new qrdecomposition(J); vector Dx = qrJ.solve(-fx); double s = 1; do // backtracking linesearch { z = x + Dx * s; fz = f(z); if (fz.norm() < (1 - s / 2) * fx.norm()) { break; } if (s < 1.0 / 32) { break; } }while((s /= 2) > 1.0 / 64); x = z; fx = fz; if (fx.norm() < eps) { break; } } return(nsteps); }//broyden
static void Main() { int n = 7, m = n; var A = new matrix(n, m); var rnd = new System.Random(); for (int i = 0; i < A.size1; i++) { for (int j = 0; j < A.size2; j++) { A[i, j] = 2 * (rnd.NextDouble() - 1); } } A.print("random matrix A:"); var b = new vector(m); for (int i = 0; i < b.size; i++) { b[i] = rnd.NextDouble(); } b.print("random vector b:\n"); var qra = new qrdecomposition(A); var x = qra.solve(b); x.print("solution x to system A*x=b:\n"); var Ax = A * x; Ax.print("check: A*x (should be equal b):\n"); if (vector.approx(Ax, b)) { WriteLine("test passed"); } else { WriteLine("test failed"); } var B = qra.inverse(); var C = (B * A); C.print("A^-1*A="); var D = (A * B); D.print("A*A^-1="); }