gpt4 book ai didi

javascript - 模拟退火

转载 作者:行者123 更新时间:2023-12-02 18:48:44 25 4
gpt4 key购买 nike

我想用 HTML 和 JavaScript 编写模拟退火代码。我想对其进行编码以进行放置,但为了简单起见,我假设所有单元格都在一行中。我有大约30个细胞。我在网上查找了一些 Material ,但找不到开始的代码。

我的伪代码如下:

Simulated_Annealing{
S = initial solution
T = initial temperature (>0)
while( T > 0 ) {
S’ = pick a random neighbor to S
C = cost of S – cost of S’
if( C > 0 ){
S = S’
} else {
r = random number in range [0…1]
m = 1/e| C/T |
if( r < m ) {
S = S’
}
}
T = reduced T;
}
}

感谢任何帮助。

谢谢。

最佳答案

在 GitHub 上快速搜索发现 https://github.com/ebobby/Jsqueens它使用模拟退火来解决九皇后问题。相关代码如下:

/**
* @author Francisco Soto <ebobby@gmail.com>
*/
var SimulatedAnnealing = (function () {
var coolingFactor = 0.0,
stabilizingFactor = 0.0,
freezingTemperature = 0.0,
currentSystemEnergy = 0.0,
currentSystemTemperature = 0.0,
currentStabilizer = 0.0,

generateNewSolution = null,
generateNeighbor = null,
acceptNeighbor = null;

function _init (options) {
coolingFactor = options.coolingFactor;
stabilizingFactor = options.stabilizingFactor;
freezingTemperature = options.freezingTemperature;
generateNewSolution = options.generateNewSolution;
generateNeighbor = options.generateNeighbor;
acceptNeighbor = options.acceptNeighbor;

currentSystemEnergy = generateNewSolution();
currentSystemTemperature = options.initialTemperature;
currentStabilizer = options.initialStabilizer;
}

function _probabilityFunction (temperature, delta) {
if (delta < 0) {
return true;
}

var C = Math.exp(-delta / temperature);
var R = Math.random();

if (R < C) {
return true;
}

return false;
}

function _doSimulationStep () {
if (currentSystemTemperature > freezingTemperature) {
for (var i = 0; i < currentStabilizer; i++) {
var newEnergy = generateNeighbor(),
energyDelta = newEnergy - currentSystemEnergy;

if (_probabilityFunction(currentSystemTemperature, energyDelta)) {
acceptNeighbor();
currentSystemEnergy = newEnergy;
}
}
currentSystemTemperature = currentSystemTemperature - coolingFactor;
currentStabilizer = currentStabilizer * stabilizingFactor;
return false;
}
currentSystemTemperature = freezingTemperature;
return true;
}

return {
Initialize: function (options) {
_init(options);
},

Step: function () {
return _doSimulationStep();
},

GetCurrentEnergy: function () {
return currentSystemEnergy;
},

GetCurrentTemperature: function () {
return currentSystemTemperature;
}
};
})();

关于javascript - 模拟退火,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10369441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com