]> gitweb.michael.orlitzky.com - octave.git/commitdiff
Add the fixed point method and some tests.
authorMichael Orlitzky <michael@orlitzky.com>
Mon, 15 Oct 2012 20:02:25 +0000 (16:02 -0400)
committerMichael Orlitzky <michael@orlitzky.com>
Mon, 15 Oct 2012 20:02:25 +0000 (16:02 -0400)
fixed_point_method.m [new file with mode: 0644]
run-tests.m

diff --git a/fixed_point_method.m b/fixed_point_method.m
new file mode 100644 (file)
index 0000000..c28a66e
--- /dev/null
@@ -0,0 +1,31 @@
+function [fixed_point, iterations] = fixed_point_method(g, epsilon, x0)
+  ## Find a fixed_point of the function `g` with initial guess x0.
+  ##
+  ## INPUTS:
+  ##
+  ##   * ``g`` - The function to iterate.
+  ##
+  ##   * ``epsilon`` - We stop when two successive iterations are within
+  ##     epsilon of each other, taken under the infinity norm. halt the
+  ##     search and return the current approximation.
+  ##
+  ## OUTPUTS:
+  ##
+  ##   * ``fixed_point`` - The fixed point that we found.
+  ##
+  ##   * ``iterations`` - The number of bisections that we performed
+  ##   during the search.
+  ##
+
+  iterations = 0;
+  prev = x0;
+  current = g(x0);
+
+  while (norm(current - prev, Inf) > epsilon)
+    prev = current;
+    current = g(current);
+    iterations = iterations + 1;
+  end
+
+  fixed_point = current;
+end
index 1682d18d20acbdf7938ba5d81c68780bd2df3351..aa285c32e38fb3f70747a75402e57ef6a8515ed2 100755 (executable)
@@ -51,3 +51,24 @@ expected_A = [1, 0, 0, 0, 0; ...
 unit_test_equals("Homework #1 problem #1 Poisson matrix is correct", ...
                 true, ...
                 expected_A == poisson_matrix(4, 0, 1));
+
+
+g = @(x) 1 + atan(x);
+expected_fp = 2.1323;
+tol = 1 / 10^10;
+x0 = 2.4;
+unit_test_equals("Homework #2 problem #5 fixed point is correct", ...
+                expected_fp, ...
+                fixed_point_method(g, tol, x0));
+
+
+h = 0.5;
+g1 = @(u) 1 + h*exp(-u(1)^2)/(1+u(2)^2);
+g2 = @(u) 0.5 + h*atan(u(1)^2 + u(2)^2);
+my_g = @(u) [g1(u), g2(u)];
+tol = 1 / 10^9;
+u0 = [1,1];
+expected_fp = [1.0729, 1.0821];
+unit_test_equals("Homework #3 problem #3i fixed point is correct", ...
+                expected_fp, ...
+                fixed_point_method(my_g, tol, u0));