why is my for loop not working?
32 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
y=@(x) x^2-4;
x1=input('Enter the value of x1:');
x2=input('Enter the value of x2:');
x3=input('Enter the value of x3:');
for i=1:100
L1=(x2-x3)/(x3-x1);
xf=x3+L1*(x3-x1);
y1=abs(y(x1));
y2= abs(y(x2));
y3=abs(y(x3));
yf=abs(y(xf));
ynext=sort([y1 y2 y3 yf]);
if y1==max(ynext)
x1=xf;
elseif y2==max(ynext)
x2=xf;
else
x3=xf;
end
if y(xf)<10^-10
break
end
end
fprintf('the root: %f\n the number of iterations: %d\n',xf,i)
3 commentaires
Jan
il y a 12 minutes
Modifié(e) : Jan
il y a 12 minutes
@KIPROTICH KOSGEY: It is hard to answer to "not working". Of course the shown code ist working and it performs exactly the instructions as defined by the code. The result differ from your expectations, but you did not mention, what you expect. What is the intention of the code?
Réponses (1)
dpb
le 13 Fév 2026 à 14:38
Déplacé(e) : Image Analyst
le 13 Fév 2026 à 15:51
Probably because you're testing floating point values for exact equality -- see isapprox and ismembertol
1 commentaire
Walter Roberson
il y a environ 15 heures
The code stores values in y1, y2, y3, yf, and then puts those values into an array using []. The values stored in the array will be bit-for-bit exact of the original values y1, y2, y3, yf (provided those are all the same datatype, which is true.) sort() of such an array will output bit-for-bit exact values, just re-arranged (exception: if different NaN representations were originally used, then the sort() will typically replace the unusual NaNs with a standard NaN.) max() of the output of sort() will result in bit-for-bit exact values.
Comparing the original value y1 to the output of max() is well defined; two bit-for-bit exact values will be compared, and they will either match or not. There is the possibility that NaN is being compared to NaN, which will give a false output.
The sort() is an unnecessary step, though: the code could easily have used
ynext=[y1 y2 y3 yf];
However...
if y(xf)<10^-10
That should likely be
if abs(y(xf))<10^-10
which in turn could be
if yf<10^-10
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!