工程数学
matlab黄金分割法(0.618法)求解优化问题x^2-x+6的极小点和极小值(进退法确定初始区间),精度为10-6;要求输出内容包括:极小点、极小值、每次迭代的a、b、al、ak的值;
代码
function [xmin, fmin, a_vals, b_vals, al_vals, ak_vals] = golds(f, a, b, epsilon) % 黄金分割法求极小值 % 输入: % f - 目标函数句柄 % a, b - 初始区间 % epsilon - 精度要求 % 输出: % xmin - 极小值点 % fmin - 极小值 % a_vals, b_vals, al_vals, ak_vals - 每次迭代的 a, b, al, ak 值 phi = (1 + sqrt(5)) / 2; % 黄金比例常数 resphi = 2 - phi; % 1 / phi % 记录每次迭代的 a, b, al, ak 值 a_vals = []; b_vals = []; al_vals = []; ak_vals = []; % 计算初始 al 和 ak al = b - resphi * (b - a); ak = a + resphi * (b - a); fal = f(al); fak = f(ak); % 迭代 while (b - a) > epsilon % 记录当前迭代的 a, b, al, ak 值 a_vals = [a_vals, a]; b_vals = [b_vals, b]; al_vals = [al_vals, al]; ak_vals = [ak_vals, ak]; if fal < fak b = ak; ak = al; fak = fal; al = b - resphi * (b - a); fal = f(al); else a = al; al = ak; fal = fak; ak = a + resphi * (b - a); fak = f(ak); end end % 极小值点和极小值 xmin = (a + b) / 2; fmin = f(xmin); end 标签:fal,ak,al,fak,5.21,vals,极小值 From: https://www.cnblogs.com/xuan-2004/p/18204352