我有遗传算法轮盘的代码。当我的迭代次数超过 1000 次时,我的程序显示错误,但当迭代次数少于 1000 次时,它的效果非常好。这是我的代码
private double[] roulleteWheel(double[] nilaiFitnessRil)
{
double[] resultRW = new double[nilaiFitnessRil.GetLength(0)];
double[] probKromosom = new double[nilaiFitnessRil.GetLength(0)];
double[] probKumulatif = new double[nilaiFitnessRil.GetLength(0)];
double pilih=0;
Random random = new Random();
double rnd;
double total = 0;
double temp = 0;
//count total fitness
for (int i = 0; i < nilaiFitnessRil.Length; i++)
{
total += nilaiFitnessRil[i];
}
listBox1.Items.Add(string.Format("total fitness adalah {0}",total));
//count probability for each chromosome
listBox1.Items.Add("result of probabilty for each chromosome");
for (int i = 0; i < nilaiFitnessRil.Length; i++)
{
probKromosom[i] = Math.Round(nilaiFitnessRil[i] / total, 4);
listBox1.Items.Add(probKromosom[i].ToString());
}
//count cumulative probability
listBox1.Items.Add("result of cumulative probabilty ");
for (int i = 0; i < probKromosom.Length; i++)
{
temp += probKromosom[i];
probKumulatif[i] = temp;
listBox1.Items.Add(probKumulatif[i].ToString());
}
//selecting a chromosome by its cumulative probability with a random value
listBox1.Items.Add(" roullete wheel");
for (int n = 0; n < resultRil.Length; n++)
{
rnd = random.NextDouble() * 1.0 - 0.0;
//listBox1.Items.Add(rnd.ToString());
for (int i = 0; i < probKumulatif.Length; i++)
{
//this is where the Index was outside the bounds of the array appear
if (probKumulatif[i] <= rnd && probKumulatif[i + 1] > rnd )
{
pilih = resultRil[i + 1];
}
else if ( rnd <= probKumulatif[0])
{
pilih = resultRil[0];
}
}
resultRil[n] = pilih;
resultRW[n] = resultRil[n];
}
PrintArray(resultRW, listBox1);
return resultRW;
}
这是程序因 Index 超出数组范围而终止的地方
if (probKumulatif[i] <= rnd && probKumulatif[i + 1] > rnd )
{
pilih = resultRil[i + 1];
}
else if ( rnd <= probKumulatif[0])
{
pilih = resultRil[0];
}