/// <summary> /// 获得当前最优解 /// </summary> /// <param name="cukoo"></param> /// <returns></returns> public Cukoo GetBestNest(Cukoo cukoo) { double fitall = 0; for (int i = 0; i < cukoo.Nest.GetLength(0); i++) { double temp1 = FitNess(DimensionalityReduction(cukoo.Nest, i)); double temp2 = FitNess(DimensionalityReduction(cukoo.newNest, i)); if (temp1 > temp2) { //old origin 无必要修改 cukoo.Nest = SetupDimensionalArray(cukoo.Nest, cukoo.newNest, i); if (temp2 < cukoo.NBest) { cukoo.NBest = temp2; cukoo.NestBest = SetupArray(cukoo.NestBest, cukoo.Nest, i); fitall = fitall + temp2; } } else { fitall = fitall + temp1; } var meanfit = DimensionalityReduction(cukoo.Nest, 0); cukoo.NestBest = meanfit.Select(x => (fitall / x)).ToArray(); } return(cukoo); }
/// <summary> /// 布谷鸟算法 /// </summary> /// <param name="lamuda"></param> /// <param name="pa"></param> /// <returns></returns> public double GetCs(double lamuda = 1, double pa = 0.25) { int[] lb = { -5, -5 }; int[] ub = { 5, 5 }; int populationSize = 20; int dim = 2; double[,] arrTemp = new double[populationSize, dim]; double[,] nest = GetRandomDimensionalArray(arrTemp, lb[0], ub[0]); double[] nestBest = DimensionalityReduction(nest, 0); double nBest = FitNess(nestBest); Cukoo cukoo = new Cukoo() { Nest = nest, NBest = nBest, NestBest = nestBest, newNest = nest }; cukoo = GetBestNest(cukoo); for (int i = 0; i < 30; i++) { double[,] nestC = new double[cukoo.Nest.GetLength(0), cukoo.Nest.GetLength(1)]; Array.Copy(cukoo.Nest, nestC, cukoo.Nest.Length); //根据莱维飞行产生新的位置 cukoo.newNest = GetNewNestVialevy(nestC, cukoo.NestBest, lb, ub, lamuda); //判断新的位置优劣进行替换 cukoo = GetBestNest(cukoo); double[,] nestE = new double[cukoo.Nest.GetLength(0), cukoo.Nest.GetLength(1)]; Array.Copy(cukoo.Nest, nestE, cukoo.Nest.Length); //丢弃部分巢穴 cukoo.newNest = EmptyNest(nestE, lb, ub, pa); cukoo = GetBestNest(cukoo); } //最优解为 cukoo.NBest return(cukoo.NBest); }