0001 function [ x,k ] = regula_falsi( f,a,b,tol,max )
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013 if a>=b;
0014 error('specifed interval invalid');
0015 elseif tol<=0;
0016 error('tol must be positive');
0017 elseif max<=0;
0018 error('max must be positive');
0019 elseif isa(f,'function_handle');
0020
0021 elseif isa(f,'double');
0022 [n,m]=size(f);
0023 if n~=1 && m~=1;
0024 error(['input must be a function handle or vector holding ',...
0025 'polynomial coefficients']);
0026 else
0027 v=poly2sym(f);
0028
0029 f=matlabFunction(v);
0030
0031 end
0032 else
0033 error(['f must be a function handle or vector holding ',...
0034 'polynomial coefficients']);
0035 end
0036
0037
0038 fa=feval(f,a);
0039 fb=feval(f,b);
0040 k=0;
0041
0042 if fa==0;
0043 x=a; return;
0044 elseif fb==0;
0045 x=b; return;
0046 elseif fa*fb>0;
0047 error('function values at endpoints have the same sign');
0048 end
0049
0050 while abs(fa)>tol && abs(fb)>tol && k<=max;
0051
0052 m=(fb*a-fa*b)/(fb-fa);
0053 fm=feval(f,m);
0054
0055 if fm==0;
0056 x=m; return;
0057 end
0058
0059 if fm*fa<0;
0060 b=m;
0061 fb=fm;
0062 else
0063 a=m;
0064 fa=fm;
0065 end
0066
0067 k=k+1;
0068 end
0069
0070 if abs(fa)<tol;
0071 x=a;
0072 else
0073 x=b;
0074 end
0075
0076 if k==max+1;
0077 disp('maximum number of iterations reached');
0078 end
0079
0080 end
0081