0.618法和二分法的MATLAB程序及实验比较最优化
最优化 实验报告一
学号:1186320… 姓名:
实验目的
能够对具体的问题用适合的最优化方法进行求解。
对同一个问题用不同的进行求解并比较优劣。
实验方法
利用MATLAB软件,用0.618法和二分法求解问题。
实验题目
书本p27
求解minf x x^2-x-1.
初始区间为[-1,1],区间精度为0.05.
求minf x x^3-2x+1的近似解,初始搜索区间为[0,3],区间精度为0.15.
minf x x^3-3*x+1,初始区间为[0,1],区间精度为0.10
minf x x^4+2*x+4;初始区间为[0,2],区间精度为0.05
minf x 3*x^4-4*x^3+12*x^2,初始区间为[-1,2],区间精度为0.02
解答
结果0.618法0.50165 0.81150.96560.7902-4.5310e-004二分法0.53130.84380.93750.7813-0.0039
迭代次数0.618法986912二分法65468
用时0.618法0.0321520.0121830.0117110.0063970.019052二分法0.1807710.16831901539240.1897400.311732从中可以看出在相同的精度下0.618法的迭代次数要比二分法的多,计算结果比较准确,而且计算的用时比二分法的少。此外程序的运行时间与电脑的负载有一定的联系。在进行比较复杂的运算时,电脑空闲空间大,就能更快的输出结果。
实验程序
①用0.618程序 function [s,phis,k,G,E] golds phi,a,b,delta,epsilon
t sqrt 5 -1 /2; h b-a; phia feval phi,a ; phib feval phi,b ;
p a+ 1-t *h; q a+t*h; phip feval phi,p ; phiq feval phi,q ;
k 1; G k,: [a, p, q, b];
while abs phib-phia epsilon | h delta if phip phiq b q; phib phiq; q p; phiq phip; h b-a; p a+ 1-t *h; phip feval phi,p ; else a p; phia phip; p q; phip phiq; h b-a; q a+t*h; phiq feval phi,q ; end k k+1; G k,: [a, p, q, b];
end
ds abs b-a ; dphi abs phib-phia ;
if phip phiq s p; phis phip;
else s q; phis phiq;
end
E [ds,dphi];
tic
[s,phis,k,G,E] golds inline 's^2-s-1' ,-1,1,5e-2,5e-2
toc
二分法:
fdff.m:
function dy fdiff x
syms x;
f x^2-x-1;
dy fdiff f ;
eff.m:
function [k,s,G] eff phi,a,b,delta,epsilon
h 0.5* b-a ;
phia feval phi,a ;phib feval phi,b ;
p a+h;
phip feval phi,p ;
k 1;G k,: [k,a,b,p,phip];
dphip subs fdiff,p ;
dphia subs fdiff,a ;
dphib subs fdiff,b ;
while abs phib-phia epsilon | h delta if dphip*dphib 0 b p;phib phip; else a p;phia phip; end h 0.5* b-a ;p a+h;phip feval phi,p ; dphip subs fdiff,p ;dphia subs fdiff,a ;dphib subs fdiff,b ; s p; k k+1;G k,: [k,a,b,p,phip];
end
tic
[k,s,G] eff inline 'x^2-x-1' ,-1,1,5e-2,5e-2
toc