How can I escape this loop and draw the diagram? (Find minimum of a function using Bisection method)

조회 수: 2 (최근 30일)
Janidu 2022년 11월 9일
댓글: Janidu 2022년 11월 9일
I need to find the minimum of the function using Bisection method. And I'm a beginner and this is the code I created. Can you show me the mistakes of this please? I need to draw the graph also.
x = [0,1]
tolerance = E1 = 0.01
thank you.
%% Find the minimum of a function using Bisection method
clc
clear
% Define givens
f = @(x) exp((x.^4 + x.^2 -x + sqrt(5))./5) + sinh((x.^3 + 21.*x + 9)./(21.*x + 6)) -3 ;
a = 0;
b = 1;
E1 = 0.01;
n = E1/10;
while b - a > n
X1 = (a + b)/2 - n ;
X2 = (a + b)/2 + n ;
if f(X1) >= f(X2)
a = X1 ;
else
b = X2 ;
end
Xmin = (X1+X2)/2;
end
L = [a , b];
plot (L,n*1,'black','LineWidth',6)
hold on
grid on

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

채택된 답변

Chandler Hall 2022년 11월 9일
편집: Chandler Hall 2022년 11월 9일
A couple issues with the exit condition for the while loop: the algorithm ultimately produces an interval [a, b] with a width of 2n, but will only exit if the interval has width n. More subtly, the proper comparison
b - a > 2n
is susceptible to floating point precision limitations. So, while mathematically speaking the interval [(a+b)/2-n, (a+b)/2+n] will always converge to an interval of width 2n, when represented as floating point values the interval may be wider after "converging". Matlab provides a function eps(x) to represent the smallest increment from the floating point value x to the next highest representable value. Values farther from zero are inherently less precise. You should use:
while b - a > 2*(n + max(eps(a), eps(b)))
to ensure the loop actually reaches its exit condition.
Regarding plotting the function, you will need to define your x-interval before 'a' and 'b' are clobbered by the while loop and using the colon operator to specify the spacing of values between the endpoints:
f = @(x) exp((x.^4 + x.^2 -x + sqrt(5))./5) + sinh((x.^3 + 21.*x + 9)./(21.*x + 6)) -3 ;
a = 0;
b = 1;
E1 = 0.01;
n = E1/10;
xs = a:E1:b;
ys = f(xs);
while b - a > 2*(n + max(eps(a), eps(b)))
X1 = (a + b)/2 - n ;
X2 = (a + b)/2 + n ;
if f(X1) >= f(X2)
a = X1 ;
else
b = X2 ;
end
Xmin = (X1+X2)/2;
end
plot (xs, ys,'black','LineWidth',6)
hold on
grid on
% plot a circle marking the minimum value
plot(Xmin, f(Xmin), 'black', 'marker', 'o', 'markersize', 20)
댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Janidu 2022년 11월 9일
Understood!
Thank you very much.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by