zoukankan      html  css  js  c++  java
  • 利用黄金分割法一维搜索的最速下降法matlab源程序

      黄金分割法以为搜索法源程序:

     1 function xmin = goldSearch(fun,a,b,eps)
     2 % ---input
     3 % fun   所求的目标函数
     4 % a     区间的下界
     5 % b     区间的上界
     6 %eps    区间的最小阀值长度
     7 % ---output
     8 % xmin 函数取极小值时自变量的值
     9 x1 = a+0.382*(b-a);
    10 x2 = a +0.618*(b-a);
    11 f1 = fun(x1);
    12 f2 = fun(x2);
    13 while abs(b-a)>eps
    14     if f1>f2
    15         a = x1;
    16         x1 = x2;
    17         x2 = a +0.618*(b-a);
    18         f1 = f2;
    19         f2 = fun(x2);
    20     else
    21         b = x2;
    22         x2 = x1;
    23         x1 = a+0.382*(b-a);
    24         f2 = f1;
    25         f1 = fun(x1);
    26     end
    27 end
    28 xmin=(b+a)/2;
    29 fmin = fun(xmin)

      最速下降法源代码:

     1 function [feval,x] = gradientDescent(fun,gfun,x0,eps)
     2 % ---input
     3 % fun   所求的目标函数
     4 % gfun  目标函数的梯度导数
     5 % x0    初始值
     6 % ---output
     7 % feval 极小值
     8 % x     极小值处自变量的值
     9 
    10 syms u % 一维寻优中目标函数的自变量
    11 grad = gfun(x0);
    12 x = x0;
    13 while norm(grad)> eps
    14     goldfex = fun(x-u*grad); %表达式
    15     goldf = inline(goldfex); %将表达式转换成关于u的匿名函数
    16     lamda = goldSearch(goldf,0,0.3,0.1); %寻找最优步长
    17     x = x-lamda*grad
    18     grad = gfun(x);
    19     norm(grad);
    20     feval = fun(x)
    21 end
    22 feval = fun(x);

      测试如下:

     1 function main
     2 clear,clc
     3 % syms x1 x2
     4 % u = [x1,x2];
     5 % fexp = 2*u(1).^2+u(2).^2;
     6 % f = inline(fexp,'u');
     7 % gfexp = jacobian(fexp);
     8 % gf = inline(gfexp,'u');
     9 x0 =[10,10,10];
    10 [fmin,x] = gradientDescent(@f,@gf,x0,0.1)
    11 
    12 function y =gf(x) %目标函数f的梯度矩阵函数
    13 % y= [4*x(1),2*x(2)];
    14 syms x1 x2 x3
    15 fexp = f([x1,x2,x3]);
    16 gfexp = jacobian(fexp);
    17 gff = inline(gfexp,'x1','x2','x3');
    18 y =gff(x(1),x(2),x(3));
    19 % y = 2*cos(x);
    20 
    21 function y = f(x) %目标函数
    22 % y=2*x(1).^2+x(2).^2;
    23 y=x(1)^2+x(2)^2+x(3)^2-10*cos(2*pi*x(1))-10*cos(2*pi*x(2))-10*cos(2*pi*x(3));
    24 % y = 8+2*sin(x);
  • 相关阅读:
    【Educational Codeforces Round 101 (Rated for Div. 2) C】Building a Fence
    【Codeforces Round #698 (Div. 2) C】Nezzar and Symmetric Array
    【Codeforces Round #696 (Div. 2) D】Cleaning
    【Codeforces Round #696 (Div. 2) C】Array Destruction
    【Educational Codeforces Round 102 D】Program
    【Educational Codeforces Round 102 C】No More Inversions
    【Good Bye 2020 G】Song of the Sirens
    【Good Bye 2020 F】Euclid's nightmare
    使用mobx入门
    requestAnimationFrame 控制速度模拟setinterval
  • 原文地址:https://www.cnblogs.com/lyfruit/p/2848426.html
Copyright © 2011-2022 走看看