Reputation: 75
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?
Upvotes: 0
Views: 56
Reputation: 1641
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
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(end),f(Roots(end)),'gs');
disp(Roots(end));
xL=df;
xR=XR;
end
end
subplot(2,1,2);
title('graph 2');
% give the wide interval again because it was changed previously
XR=2;
xL=-2;
x0=fzero(f,xL);
Roots = BisectionM(f,xR,xL,eps);
plot(1:length(Roots),ones(length(Roots),1)*x0, 'g');
hold on ;
plot(1:length(Roots),Roots,'Marker', '.');
xlabel('iteration number')
BisectionM.m
function Roots = BisectionM(f,xR,xL,eps)
% no preallocation because of while
ii = 1;
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(ii) = xM;
ii = ii + 1;
end
end
Upvotes: 1