我有遺傳算法的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