Any value (different values) I enter for TOLERANCE and ITERATION gives the same results(Answer( . It is supposed to give different answers . I don't know why this is occurring.
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Jim Wilson Owusu
il 14 Mag 2021
Modificato: Stephen23
il 14 Mag 2021
clear all
close all
clc
tol=input ('Enter TOLERANCE number:') ;
n =input('Enter ITERATION number:');
n=100;
f=@(x) (x+1-2*sin(pi*x));
a=0;
b=0.5;
if f(a) * f(b)>0
warning('ít is not applicable:')
elseif f(a)==0
fprintf('The root is %d', a)
elseif f(b)==0
fprintf('The root is %d', b)
end
pre=0;
for i=1:n
c=(a+b)/2;
if f(c)==0
fprintf('The root is: %d\n', c)
elseif f(c)*f(b)<0
a=c;
elseif f(c)*f(a)<0
b=c;
end
if abs(c-pre)<=tol
break;
end
pre=c;
end
fprintf('The root is %g with the %.3d tolerance',c,tol)
plot(c, f(c),f(a), 'ro')
0 Commenti
Risposta accettata
Stephen23
il 14 Mag 2021
Modificato: Stephen23
il 14 Mag 2021
tol = 0.001;
n = 100;
f = @(x) (x+1-2*sin(pi*x));
fplot(f,[0,0.5])
a = 0;
b = 0.5;
pre=0;
for i = 1:n
c = (a+b)/2;
if f(c)==0
fprintf('The root is: %d\n', c)
elseif f(c)*f(b)<0
a=c;
else % !!!!!!!!!!!! Remove ELSEIF here !!!!!!!!!
b=c;
end
if abs(c-pre)<=tol
break;
end
pre=c;
end
fprintf('The root is %g with the %g tolerance in %d iterations',c,tol,i)
0 Commenti
Più risposte (1)
Walter Roberson
il 14 Mag 2021
You exit the loop when you reach the tolerance.
What happens if you exit the loop no later than 5 iterations? Then giving 20 instead would not produce any change in output. You should display the number of iterations used as well.
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!