diff options
Diffstat (limited to 'usth/MATH2.2/labwork/1/bisect.m')
-rw-r--r-- | usth/MATH2.2/labwork/1/bisect.m | 36 |
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 |