How can I escape this loop and draw the diagram? (Find minimum of a function using Bisection method)
조회 수: 4 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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)
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!