Borrar filtros
Borrar filtros

False Position Method (Plot)

47 visualizaciones (últimos 30 días)
Brain Adams
Brain Adams el 23 de Mzo. de 2021
Comentada: Alan Stevens el 23 de Mzo. de 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

Respuestas (1)

Alan Stevens
Alan Stevens el 23 de Mzo. de 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 comentarios
Brain Adams
Brain Adams el 23 de Mzo. de 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 el 23 de Mzo. de 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')

Iniciar sesión para comentar.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by