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

KIPROTICH KOSGEY
KIPROTICH KOSGEY 2026년 2월 16일
Anyone out there to shed some light on the above?
Torsten
Torsten 2026년 2월 16일
편집: Torsten 2026년 2월 16일
Should your code be an implementation of the secant method to get a root of y ? Or what is its purpose ?
Jan
Jan 2026년 2월 17일
편집: Jan 2026년 2월 17일
@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?

댓글을 달려면 로그인하십시오.

답변 (1개)

dpb
dpb 2026년 2월 13일
이동: Image Analyst 2026년 2월 13일

1 개 추천

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.

댓글 수: 1

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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2026년 2월 13일

댓글:

2026년 2월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by