why is my for loop not working?
Ältere Kommentare anzeigen
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 Kommentare
KIPROTICH KOSGEY
am 16 Feb. 2026
@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?
Antworten (1)
dpb
am 13 Feb. 2026
Verschoben: Image Analyst
am 13 Feb. 2026
1 Stimme
Probably because you're testing floating point values for exact equality -- see isapprox and ismembertol
1 Kommentar
Walter Roberson
am 17 Feb. 2026
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
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!