Java模拟退火算法的伪代码

6

我目前正在一个名为TSP的项目上工作,试图将一些模拟退火伪代码转换成Java。我过去成功地将伪代码转换成Java代码,但是这次却无法成功转换。

伪代码如下:

T0(T and a lowercase 0)    Starting temperature
Iter    Number of iterations
λ    The cooling rate

1.  Set T = T0 (T and a lowercase 0)
2.  Let x = a random solution
3.  For i = 0 to Iter-1
4.  Let f = fitness of x
5.  Make a small change to x to make x’
6.  Let f’ = fitness of new point
7.  If f’ is worse than f then
8.      Let p = PR(f’, f, Ti (T with a lowercase i))
9.      If p > UR(0,1) then
10.         Undo change (x and f)
11.     Else
12.         Let x = x’
13.     End if
14.     Let Ti(T with a lowercase i) + 1 = λTi(λ and T with a lowercase i)
15. End for
Output:  The solution x

如果有人能够用Java给我展示这个的基本标记,我将不胜感激 - 我似乎无法理解它!
我正在跨多个类使用多个函数(我不会列出来,因为这与我所问的问题无关)。我已经有了一个smallChange()方法和一个fitness函数 - 是否有可能需要创建几个不同版本的该方法?例如,我有像下面这样的东西:
public static ArrayList<Integer> smallChange(ArrayList<Integer> solution){

//Code is here.

}

我是否需要另一个版本的这个方法来接受不同的参数?类似于:

public static double smallChange(double d){

//Code is here.

}

我只需要一个基本概念,知道这段内容在Java中应该长成什么样子 - 一旦我知道正确的语法应该是什么样子,我就能够将其适应到我的代码中,但是我似乎无法跨越这个障碍。


在这里,您还可以查看我的实现(部分)。它被保持得非常通用。https://dev59.com/PnPYa4cB1Zd3GeqPmLAN#18657788 - mike
3个回答

5
基本代码应该如下所示:
public class YourClass {
  public static Solution doYourStuff(double startingTemperature, int numberOfIterations, double coolingRate) {
    double t = startingTemperature;
    Solution x = createRandomSolution();
    double ti = t;

    for (int i = 0; i < numberOfIterations; i ++) {
      double f = calculateFitness(x);
      Solution mutatedX = mutate(x);
      double newF = calculateFitness(mutatedX);
      if (newF < f) {
        double p = PR(); // no idea what you're talking about here
        if (p > UR(0, 1)) { // likewise
          // then do nothing
        } else {
          x = mutatedX;
        }
        ti = t * coolingRate;
      }
    }
    return x;
  }

  static class Solution {
    // no idea what's in here...
  }
}

现在,如果你想要不同版本的smallChange()方法-完全可以做到,但你需要稍微了解一下继承


2
我有一种感觉,ti = t * coolingRate; 应该是 ti = ti * coolingRate; - Deleplace

5

3

此外,这里还有一种基于Java的模拟退火算法教学方法(含示例代码):

Neller, Todd. 教授随机局部搜索,载于I. Russell和Z. Markov编辑的《第18届国际FLAIRS会议论文集》(FLAIRS-2005),AAAI Press出版,2005年5月15日至17日,佛罗里达州克利尔沃特海滩,第8-13页。

相关资源、参考资料和演示在此处:http://cs.gettysburg.edu/~tneller/resources/sls/index.html


这篇论文真的值得一读。它通过编码示例完美地激励和解释了模拟退火的功能。他们提供的代码可以轻松地适应任何类型的优化问题。 - Michael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接