How can I make a table bisection method and put all iterables step by step?

4 次查看(过去 30 天)
a = input('a = ');
b = input('b = ');
E = input('Error = ');
N = log((b-a)/E)/(log(2))
f = @(x) x^2 - 3;
format long
for i = 1:N
c =(a+b)/2;
T = table(N,a,b,c,f(c));
T(N:5,:)
disp(T);
if f(c) * f(a) > 0
a = c;
else
b = c;
end
% if (abs(b-a) / 2^N) <= E || f(c) == 0
% break
% end
end
final_ans = c;
fprintf('root is %f\n',final_ans);
% OUTPUT
%N a b c Var5
%________________ _______ ____ ________ ______________
%7.64385618977472 1.71875 1.75 1.734375 0.008056640625
%root is 1.734375

采纳的回答

Jan
Jan 2021-3-31
编辑:Jan 2021-3-31
With your current method the table is overwritten in each iteration. Create the table before the loop and insert the new values only.
[EDITED] Some code:
a = 1;
b = 2;
E = 1e-6;
N = ceil(log((b - a) / E) / log(2)); % CEIL() !
f = @(x) x^2 - 3;
T = table('Size', [N, 5], ...
'VariableTypes', {'double', 'double', 'double', 'double', 'double'}, ...
'VariableNames', {'N', 'a', 'b', 'c', 'fc'});
for i = 1:N
c = (a + b) / 2;
T(i, :) = {i, a, b, c, f(c)}; % Fill in data in existing table
if f(c) * f(a) > 0
a = c;
else
b = c;
end
end
disp(T)
  2 个评论
Mahdi Ayyad
Mahdi Ayyad 2021-3-31
But this is the output
% OUTPUT
%N a b c Var5
%________________ _______ ____ ________ ______________
%7.64385618977472 1.71875 1.75 1.734375 0.008056640625
%root is 1.734375
it's not overwritten, but i tried to put the table before the loop and still the same.
Jan
Jan 2021-3-31
编辑:Jan 2021-3-31
"i tried to put the table before the loop" - Then please post the corresponding code. This is more efficient for solving your problem than letting the readers guess, what you have done exactly.
I still do not like the table syntax and avoid using this type in productive code. But see [EDITED] in my answer for an explicit example.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by