Filter löschen
Filter löschen

False Position Method (Plot)

47 Ansichten (letzte 30 Tage)
Brain Adams
Brain Adams am 23 Mär. 2021
Kommentiert: Alan Stevens am 23 Mär. 2021
Hi everyone, I wrote a code that finds the root of the equation using False Position Method. I would like to ask that, how can I plot the root as a function of iteration number and approximate error as a function of itteration number? Thanks in advance to all who want to help!
f = @(x) 1000*x^3 + 3000*x - 15000;
x_l = 0;
x_u = 4;
if f(x_l)*f(x_u) > 0
fprintf('There is no solution in the given interval');
return
elseif f(x_l) == 0
fprintf('%f is the solution',x_l);
elseif f(x_u) == 0
fprintf('%f is the solution', x_u);
end
fprintf('i xl xu xm\n');
for i = 1:1000
xm = x_u - (x_l-x_u)*f(x_u)/(f(x_l)-f(x_u));
fprintf('%i %f %f %f\n',i,x_l,x_u,xm)
if abs(f(xm)) < 0.0001
return
end
if f(x_l)*f(xm) < 0
x_u = xm;
elseif f(x_u)*f(xm) < 0
x_l = xm;
end
end

Antworten (1)

Alan Stevens
Alan Stevens am 23 Mär. 2021
Like this:
f = @(x) 1000*x^3 + 3000*x - 15000;
x_l = 0;
x_u = 4;
if f(x_l)*f(x_u) > 0
fprintf('There is no solution in the given interval');
return
elseif f(x_l) == 0
fprintf('%f is the solution',x_l);
elseif f(x_u) == 0
fprintf('%f is the solution', x_u);
end
fprintf('i xl xu xm\n');
for i = 1:100
xm(i) = x_u - (x_l-x_u)*f(x_u)/(f(x_l)-f(x_u));
%fprintf('%i %f %f %f\n',i,x_l,x_u,xm)
if abs(f(xm(i))) < 0.0001
break
end
if f(x_l)*f(xm(i)) < 0
x_u = xm(i);
elseif f(x_u)*f(xm(i)) < 0
x_l = xm(i);
end
end
i = 1:numel(xm);
plot(i,xm,'o'),grid
xlabel('iteration number')
ylabel('root approximation')
  2 Kommentare
Brain Adams
Brain Adams am 23 Mär. 2021
Thanks! It is much more clear now. I am trying to plot other graphic. Unfortuanetly, I couldn't plot approximate error as a function of itteration number. Can you help me on that too?
Alan Stevens
Alan Stevens am 23 Mär. 2021
Depends on what you think of as the approximate error. If you mean the change in xm from one iteration to the next, then try the following:
f = @(x) 1000*x^3 + 3000*x - 15000;
x_l = 0;
x_u = 4;
if f(x_l)*f(x_u) > 0
fprintf('There is no solution in the given interval');
return
elseif f(x_l) == 0
fprintf('%f is the solution',x_l);
elseif f(x_u) == 0
fprintf('%f is the solution', x_u);
end
xmold = (x_l + x_u)/2;
%fprintf('i xl xu xm\n');
for i = 1:100
xm(i) = x_u - (x_l-x_u)*f(x_u)/(f(x_l)-f(x_u));
deltax(i) = abs(xm(i)-xmold);
%fprintf('%i %f %f %f\n',i,x_l,x_u,xm)
if abs(f(xm(i))) < 0.0001
break
end
if f(x_l)*f(xm(i)) < 0
x_u = xm(i);
elseif f(x_u)*f(xm(i)) < 0
x_l = xm(i);
end
xmold = xm(i);
end
i = 1:numel(xm);
plot(i,xm,'o'),grid
xlabel('iteration number')
ylabel('root approximation')
figure
semilogy(i,deltax,'o'),grid
xlabel('iteration number')
ylabel('error')

Melden Sie sich an, um zu kommentieren.

Produkte


Version

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by