I want to plot the graph of the numerical solution of bisection method and show how it get close to the real solution . my code:
% f=input('please enter the function:');
% xL=input('please enter the limits .from:');
% XR=input('to:');
% eps=input('please enter epsilon:');
f=@(x)x.^2-1;
XR=2;
xL=-2;
XL=xL ;
eps=0.001;
subplot(2,1,1);
title('graph 1');
ezplot(f);
hold on ;
% line([0 0],40);
% line(-40,[0 0]);
plot(XR,f(XR),'r*');
plot(xL,f(xL),'r*');
disp( 'the answers is : ');
for df=xL:0.15:XR
if f(xL)*f(df)<= 0
xR=df;
Roots = BisectionM(f,xR,xL,eps);
plot(Roots,f(Roots),'gs');
disp(Roots);
xL=df;
xR=XR;
end
end
subplot(2,1,2);
title('graph 2');
x0=fzero(f,xL);
sol = BisectionM(f,xR,xL,eps);
plot(1:1:100,ones(1,100)*x0);
hold on ;
plot(1:1:100,sol);
the function :
function[sol,Roots] = BisectionM(f,xR,xL,eps)
while abs(xR - xL) > eps
xM = (xR + xL) / 2;
if (f(xL))*(f(xM)) > 0
xL = xM;
sol=xM;
plot(xL,f(xL),'.');
else
xR = xM;
plot(xR,f(xR),'.');
sol=xM;
end
Roots = xM;
end
end
I don't know how to plot this so it will get closer to the solution (the blue line at the end). anyone?
I do not understand many things in your code, e.g. why
BisectionM
has two identical outputs under different variable names (sol
,Roots
), moreover only one output is used throughout the main function. Besides here is my guess what you might want:The figure shows how the numerical solution converges with respect to iteration number. For this you have to store the iteration results in a vector (
sol
), please see below the modified code:main.m
BisectionM.m