why is my for loop not working?

19 Ansichten (letzte 30 Tage)
KIPROTICH KOSGEY
KIPROTICH KOSGEY am 13 Feb. 2026 um 10:16
Verschoben: Image Analyst am 13 Feb. 2026 um 15:51
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)

Antworten (1)

dpb
dpb vor etwa 9 Stunden
Verschoben: Image Analyst vor etwa 7 Stunden
Probably because you're testing floating point values for exact equality -- see isapprox and ismembertol
See the <example in eq for more> for what is likely the cause.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by