Java 模拟退火算法(伪代码实现)

我目前正在做一个项目 (TSP),并尝试将一些模拟退火伪代码转换为 Java 代码。 过去我曾成功地将伪代码转换为 Java 代码,但这次却无法成功转换。

伪代码如下:

T0(T and a lowercase 0)    Starting temperatureIter    Number of iterationsλ    The cooling rate1.  Set T = T0 (T and a lowercase 0)2.  Let x = a random solution3.  For i = 0 to Iter-14.  Let f = fitness of x5.  Make a small change to x to make x’6.  Let f’ = fitness of new point7.  If f’ is worse than f then8.      Let p = PR(f’, f, Ti (T with a lowercase i))9.      If p > UR(0,1) then10.         Undo change (x and f)11.     Else12.         Let x = x’13.     End if14.     Let Ti(T with a lowercase i) + 1 = λTi(λ and T with a lowercase i)15. End forOutput:  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 中编写这个有一个基本的了解 – 一旦我知道它在正确的语法中应该是什么样子,我就能够将它应用到我的代码中,但是我似乎无法克服这个障碍。


回答:

基本代码应该像这样:

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() 方法的不同版本 – 完全可以做到,但你必须阅读一些关于继承的内容。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注