Test our (P)CGM implementation against Octave's.
[octave.git] / tests / conjugate_gradient_method_tests.m
1 A = [5,1,2; ...
2 1,6,3;
3 2,3,7];
4
5 b = [1;2;3];
6
7 x0 = [1;1;1];
8
9 ## Solved over the rationals.
10 expected = [2/73; 11/73; 26/73];
11 actual = conjugate_gradient_method(A, b, x0, 1e-6, 1000);
12 diff = norm(actual - expected);
13
14 unit_test_equals("CGM works on an example", ...
15 true, ...
16 norm(diff) < 1e-6);
17
18
19 # Let's test Octave's pcg() against our method on some easy matrices.
20 max_iterations = 100000;
21 tolerance = 1e-11;
22
23 for n = [ 5, 10, 25, 50, 100 ]
24 A = random_positive_definite_matrix(5, 1000);
25
26 # Assumed by Octave's implementation when you don't supply a
27 # preconditioner.
28 x0 = zeros(5, 1);
29 b = unifrnd(-1000, 1000, 5, 1);
30 [o_x, o_flag, o_relres, o_iter] = pcg(A, b, tolerance, max_iterations);
31 [x, k] = conjugate_gradient_method(A, b, x0, tolerance, max_iterations);
32
33 diff = norm(o_x - x);
34 msg = sprintf("Our CGM agrees with Octave's, n=%d.", n);
35 unit_test_equals(msg, true, norm(diff) < 1e-10);
36 end