How do I count how many iterations my root is in a smaller interval?

1 vue (au cours des 30 derniers jours)
Matthew Worker
Matthew Worker le 11 Nov 2017
Modifié(e) : Rena Berman le 21 Mar 2018
In my code I need to display in the command line how many of the iterations my root was in the smaller interval. I am not entirely sure what this means, but I'm hoping someone does and can give me a hand to work out what I'm missing. At the moment the command line displays the same number of iterations for both the iterations to the root and how many iterations the root was in the smaller interval.
Code removed. Question has been answered.

Réponse acceptée

Mischa Kim
Mischa Kim le 11 Nov 2017
In each iteration you have two intervals, [a,c] and [c,b]. Compute the size of both intervals and use the last if-else condition in your code to increment itc.
  1 commentaire
Mischa Kim
Mischa Kim le 11 Nov 2017
I used
f = @(x) sqrt(x) - cos(x);
[a,b,it,itc] = WB(f,0,15,0.25,1e-5)
with (please double-check)
function [a,b,it,itc] = WB(f,a,b,w,tol)
it=0;
itc=0;
fa=f(a);
fb=f(b);
if fa*fb>0
error('Not guaranteed a root in interval [a,b]');
end
if abs(fa)<abs(fb)
fprintf('The root is probably closer to a than b\n');
else
abs(fa)>abs(fb);
fprintf('The root is probably closer to b than a\n');
end
while (b-a)/2>tol
c = (1-w)*a+w*b;
% fc = f(c); % not really needed
% if fc == 0
% return
% end
x = abs(a-c);
y = abs(c-b);
if f(a)*f(c)<0
b = c;
if x<y
itc = itc + 1;
end
else
a = c;
if y<x
itc = itc + 1;
end
end
it = it+1;
end
fprintf('Final interval: [%f, %f] with %d iterations and %d iterations where the root was in the smaller interval\n',a,b,it,itc)
end

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by