为什么这种递归方法与 while-true 循环的工作方式不同?
我正在第一次尝试遗传算法,并在尝试实现池选择时遇到了一个奇怪的错误。我最初的方法使用递归调用循环,直到满足参数,但这破坏了我的进化。当我将其切换到 while 循环时,一切都突然开始工作。然后,我尝试采用旧的递归方法(acceptRejectBad1)并翻转 if 语句以匹配 while 循环,突然它起作用了,但仍然比 while 循环方法花费了更多的代数才能达到目标。无论如何,使用 while 循环在这里可能更有意义,但我想了解为什么递归方法会失败。谁能向我解释为什么这三种方法的行为如此不同?
//recursive call method one
Guess acceptRejectBad1(double maxFit) {
Guess parent = this.guesses[ThreadLocalRandom.current().nextInt(this.guesses.length)];
if (parent.fitness <= ThreadLocalRandom.current().nextDouble(maxFit)) {
return this.acceptRejectBad(maxFit);
} else {
return parent;
}
}
//recursive call method two
Guess acceptRejectBad2(double maxFit) {
Guess parent = this.guesses[ThreadLocalRandom.current().nextInt(this.guesses.length)];
if (parent.fitness > ThreadLocalRandom.current().nextDouble(maxFit)) {
return parent;
} else {
return this.acceptRejectBad(maxFit);
}
}
//while-true loop method
Guess acceptReject(double maxFit) {
while (true) {
Guess parent = this.guesses[ThreadLocalRandom.current().nextInt(this.guesses.length)];
if (parent.fitness > ThreadLocalRandom.current().nextDouble(maxFit)) {
return parent;
}
}
}
I'm working on my first endeavor into genetic algorithms and came across a weird bug when trying to implment pool selection. My original method used a recursive call to loop until a perameter was met, but this broke my evolution. When I switched it to a while loop everything worked suddenly. Then, I tried taking my old recursive method (acceptRejectBad1) and flipped the if statement to match the while loop, suddenly it worked but still took significantly more generations to reach the goal than the while loop method. Using a while loop might make more sense here anyway but I would like to understand why the recursive methods break down. Can anyone explain to me why these three methods behave so differently?
//recursive call method one
Guess acceptRejectBad1(double maxFit) {
Guess parent = this.guesses[ThreadLocalRandom.current().nextInt(this.guesses.length)];
if (parent.fitness <= ThreadLocalRandom.current().nextDouble(maxFit)) {
return this.acceptRejectBad(maxFit);
} else {
return parent;
}
}
//recursive call method two
Guess acceptRejectBad2(double maxFit) {
Guess parent = this.guesses[ThreadLocalRandom.current().nextInt(this.guesses.length)];
if (parent.fitness > ThreadLocalRandom.current().nextDouble(maxFit)) {
return parent;
} else {
return this.acceptRejectBad(maxFit);
}
}
//while-true loop method
Guess acceptReject(double maxFit) {
while (true) {
Guess parent = this.guesses[ThreadLocalRandom.current().nextInt(this.guesses.length)];
if (parent.fitness > ThreadLocalRandom.current().nextDouble(maxFit)) {
return parent;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论