False Position Method (Plot)

47 次查看(过去 30 天)
Brain Adams
Brain Adams 2021-3-23
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

回答(1 个)

Alan Stevens
Alan Stevens 2021-3-23
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 个评论
Brain Adams
Brain Adams 2021-3-23
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 2021-3-23
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')

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Digital Filter Analysis 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by