False Position Method (Plot)
143 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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 个评论
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')
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!