我有遗传算法的Roullete Wheel的代码。我的程序显示错误时,我的迭代超过1000次迭代,但它工作得很好,当迭代低于1000 这里是我的代码索引超出了数组的范围。 C#
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;
}
这是程序被终止指数的原因是该范围之外该阵列
if (probKumulatif[i] <= rnd && probKumulatif[i + 1] > rnd)
{
pilih = resultRil[i + 1];
}
else if (rnd <= probKumulatif[0])
{
pilih = resultRil[0];
}
藏在你发布的任何问题吗? – 2013-04-23 03:31:27
当迭代次数超过1000次时,程序总是终止,但是当它小于1000时,程序非常好。迭代我应该怎么做? – Christy 2013-04-23 03:36:26