MATLAB: How to write the MatLab code for the bisection method if we use |p(i)−p(i−1)|<ξ as a stopping criteria

MATLABnumerical method

function [akar,langkah]=bagidua3(a,b,tol)
iffeval('fun',a)*feval('fun',b)>0
error('akarnyatidakterjamin')
end
langkah=0;
akar=[];
p=(a+b)/2;fp=feval('fun',p);
while abs(b-a)>tol;
langkah=langkah+1;
p=(a+b)/2;
akar=[akar,p];
fa=feval('fun',a);
fp=feval('fun',p);
if sign(fa)*sign(fp)<0
a=a;
b=p;
else
a=p;
b=b;
end
end
function y=fun(x)
y=x.^3-4*(x.^2)+sin(x)+1;
I know its somewhat look like this. But how i change it?

Best Answer

So just remember the former value of p and compare the changes equivalently to measuring the distance between a and b:
...
p = a;
oldp = inf;
while abs(b - a) > tol && abs(p - oldp) > xsi
langkah = langkah+1;
oldp = p;
p = (a + b) / 2;
akar = [akar, p];
fa = fun(a);
fp = fun(p);
if sign(fa) * sign(fp) < 0
b = p; % But not a=a !!!
else
a = p; % But not b=b !!!
end
end
Avoid confusing lines like a=a. fun(a) is nicer than feval('fun', a) and it allows to provide a function handle as input.
Related Question