1、原创模拟退火算法 /* 模拟退火法求函数 f(x,y) = 5sin(xy) + x2 + y2 的最小值* 日期:2004-4-16* 作者:ARMYLAU* EMAIL:* 结束条件为两次最优解之差小于某小量*/using System;namespace SimulateAnnealingclass Class1/ 要求最优值的目标函数static double ObjectFunction( double x, double y )double z = 0.0;z = 5.0 * Math.Sin(x*y) + x*x + y*y;return z;STAThreadstatic vo
2、id Main(string args)/ 搜索的最大区间const double XMAX = 4;const double YMAX = 4;/ 冷却表参数int MarkovLength = 10000; / 马可夫链长度double DecayScale = 0.95; / 衰减参数double StepFactor = 0.02; / 步长因子double Temperature = 100; / 初始温度double Tolerance = 1e-8; / 容差double PreX,NextX; / prior and next value of x double PreY,Ne
3、xtY; / prior and next value of y double PreBestX, PreBestY; / 上一个最优解double BestX,BestY; / 最终解double AcceptPoints = 0.0; / Metropolis 过程中总接受点Random rnd = new Random(); / 随机选点PreX = -XMAX * rnd.NextDouble() ;PreY = -YMAX * rnd.NextDouble();PreBestX = BestX = PreX;PreBestY = BestY = PreY;/ 每迭代一次退火一次(降温
4、), 直到满足迭代条件为止 doTemperature *=DecayScale;AcceptPoints = 0.0;/ 在当前温度 T 下迭代 loop(即 MARKOV 链长度) 次for (int i=0;i / 1) 在此点附近随机选下一点doNextX = PreX + StepFactor*XMAX*(rnd.NextDouble()-0.5);NextY = PreY + StepFactor*YMAX*(rnd.NextDouble()-0.5);while ( !(NextX = -XMAX PreBestY = BestY;/ 此为新的最优解BestX=NextX;Bes
5、tY=NextY;/ 3) Metropolis 过程if( ObjectFunction(PreX,PreY) - ObjectFunction(NextX,NextY) 0 )/ 接受, 此处 lastPoint 即下一个迭代的点以新接受的点开始PreX=NextX;PreY=NextY;AcceptPoints+;elsedouble change = -1 * ( ObjectFunction(NextX,NextY) - ObjectFunction(PreX,PreY) ) / Temperature ;if( Math.Exp(change) rnd.NextDouble() )
6、PreX=NextX;PreY=NextY;AcceptPoints+;/ 不接受, 保存原解Console.WriteLine(“0,1,2,3“,PreX, PreY, ObjectFunction ( PreX, PreY ), Temperature); while( Math.Abs( ObjectFunction( BestX,BestY) ObjectFunction (PreBestX, PreBestY) Tolerance );Console.WriteLine(“最小值在点:0,1“,BestX, BestY);Console.WriteLine( “最小值为:0“,ObjectFunction(BestX, BestY) );