public void SparseSquareMatrixSolutionAgreement() { Random rng = new Random(2); int n = 16; //for (int n = 8; n < 100; n+= 11) { // create dense and sparse matrices with the same entries SquareMatrix M = new SquareMatrix(n); SparseSquareMatrix S = new SparseSquareMatrix(n); for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { if (rng.NextDouble() < 0.5) { M[r, c] = rng.NextDouble(); S[r, c] = M[r, c]; } } } // pick a RHS ColumnVector b = new ColumnVector(n); for (int i = 0; i < n; i++) { b[i] = rng.NextDouble(); } // solve each ColumnVector Mx = M.LUDecomposition().Solve(b); ColumnVector Sx = S.Solve(b); // the solutions should be the same Assert.IsTrue(TestUtilities.IsNearlyEqual(Mx, Sx, TestUtilities.TargetPrecision * 100.0)); //} }
public void SparseSquareMatrixPotential() { // An 2D electrostatic boundary value problem in cartesian coordinates // A square of length n, with specified constant potentials on each wall // Discritized Laplace equation is // u_{x,y-1} + u_{x+1,y} + u_{x,y+1} + u_{x-1,y} - 4 u_{x,y} = 0 // Number interior points sequentially row-wise i.e. i = x + n * y // Points nearest the walls will pick up a boundary value, which because it is not a variable we move to the RHS // Points closer to the interior pick up no boundary value, so their RHS is zero int n = 100; double pn = 0.0; double pe = 1.0; double ps = 0.0; double pw = 1.0; SparseSquareMatrix A = new SparseSquareMatrix(n * n); ColumnVector b = new ColumnVector(n * n); // set up A and b for (int y = 0; y < n; y++) { for (int x = 0; x < n; x++) { int i = x + n * y; // center value A[i, i] = 4.0; // north if (y == 0) { b[i] += pn; } else { int j = x + n * (y - 1); A[i, j] = -1.0; } // east if (x == (n - 1)) { b[i] += pe; } else { int j = (x + 1) + n * y; A[i, j] = -1.0; } // south if (y == (n - 1)) { b[i] += ps; } else { int j = x + n * (y + 1); A[i, j] = -1.0; } // west if (x == 0) { b[i] += pw; } else { int j = (x - 1) + n * y; A[i, j] = -1.0; } } } ColumnVector u = A.Solve(b); for (int y = 0; y < 10; y++) { for (int x = 0; x < 10; x++) { int i = x + n * y; Console.Write("{0} ", u[i]); } Console.WriteLine(); } Console.WriteLine(PotentialSolution(1, 2, n)); }