about summary refs log tree commit diff
path: root/usth/MATH2.2/labwork/1/bisect.m
diff options
context:
space:
mode:
authorNguyễn Gia Phong <vn.mcsinyx@gmail.com>2019-12-16 21:31:18 +0700
committerNguyễn Gia Phong <vn.mcsinyx@gmail.com>2019-12-16 21:31:18 +0700
commite461df7573c2b7b7e26c965d8cf2d8e175d67378 (patch)
tree193b8439edac52c1749764395fe5f7787889eda9 /usth/MATH2.2/labwork/1/bisect.m
parentc1008fe39217be7f91f0ea23483e747bfbc5743e (diff)
downloadcp-e461df7573c2b7b7e26c965d8cf2d8e175d67378.tar.gz
[usth/MATH2.2] Numerical Methods
The future starts now.
Diffstat (limited to 'usth/MATH2.2/labwork/1/bisect.m')
-rw-r--r--usth/MATH2.2/labwork/1/bisect.m36
1 files changed, 36 insertions, 0 deletions
diff --git a/usth/MATH2.2/labwork/1/bisect.m b/usth/MATH2.2/labwork/1/bisect.m
new file mode 100644
index 0000000..1d9e99f
--- /dev/null
+++ b/usth/MATH2.2/labwork/1/bisect.m
@@ -0,0 +1,36 @@
+function [x fx ea iter] = bisect (f, xl, xu, es = 0.0001, maxit = 50)
+  % uses bisection method to find the root of f,
+  % with xl and xu being lower and upper guesses,
+  % es being desired relative error
+  % and maxit being maximum allowable iterations
+  % to return the real root x, fx = f(x),
+  % approximate relative error ea (%)
+  % and number of iterations iter
+  nargin < 3 && error ('bisect requires at least 3 arguments');
+  [fl fu iter] = deal (f (xl), f (xu), 0);
+  if (fl == 0)
+    [x fx ea] = deal (xl, 0, 0);
+    return;
+  elseif (fu == 0)
+    [x fx ea] = deal (xu, 0, 0);
+    return;
+  end
+  fl * fu < 0 || error ('no sign change');
+
+  [x ea] = deal (xl, 100);
+  while (ea > es && iter++ < maxit) % yes, I use Octave only
+    [xold x] = deal (x, (xl + xu) / 2);
+    fx = f (x);
+    if (fx == 0)
+      ea = 0;
+      break;
+    elseif (x)
+      ea = abs ((x - xold) / x) * 100;
+    end
+    if (f (xl) * fx < 0)
+      xu = x;
+    else
+      xl = x;
+    end
+  end
+end