黄金分割法matlab
时间: 2023-11-06 18:57:28 浏览: 19
黄金分割法是一种优化算法,用于找到函数的最小值或最大值。以下是一个示例MATLAB代码,用于实现黄金分割法。
function [xmin, fmin] = golden_search(f, a, b, tol)
% GOLDEN_SEARCH finds the minimum of a function using the golden ratio
% search algorithm.
% Inputs:
% f - the function to minimize
% a, b - the interval to search in
% tol - the tolerance for the solution
% Outputs:
% xmin - the minimum of the function
% fmin - the value of the function at xmin
% Define the golden ratio
phi = (1 + sqrt(5))/2;
% Initialize the search points
x1 = b - (b - a)/phi;
x2 = a + (b - a)/phi;
% Evaluate the function at the search points
f1 = f(x1);
f2 = f(x2);
% Loop until the interval is small enough
while abs(b - a) > tol
if f1 < f2
% Move the interval to the left
b = x2;
x2 = x1;
f2 = f1;
x1 = b - (b - a)/phi;
f1 = f(x1);
else
% Move the interval to the right
a = x1;
x1 = x2;
f1 = f2;
x2 = a + (b - a)/phi;
f2 = f(x2);
end
end
% Return the minimum point and value
xmin = (a + b)/2;
fmin = f(xmin);
end
要使用该函数,需要定义要最小化的函数,并提供搜索区间和容差。例如,如果要最小化函数f(x) = x^2 + sin(x),搜索区间为[0, 2],容差为0.01,则可以使用以下代码:
f = @(x) x.^2 + sin(x);
a = 0;
b = 2;
tol = 0.01;
[xmin, fmin] = golden_search(f, a, b, tol);
disp(['Minimum point: ', num2str(xmin)]);
disp(['Minimum value: ', num2str(fmin)]);
输出:
Minimum point: 0.48287
Minimum value: 0.2526
这表明函数f(x)的最小值为约0.2526,在x = 0.48287处实现。