【发布时间】:2018-05-04 03:40:29
【问题描述】:
我有一个双精度数组列表,每次迭代算法时都会更新它。我想将完整的数字列表输出到文件中,但它只输出一个值而不是整个列表。我使用简单的模拟退火本地搜索。每次评估后,我将新值存储在一个数组中,然后我想将列表的所有值输出到一个文件中。
我的代码:
while (eval < 50) {
//Pick two positions on the grid
int Pos1 = (int) (Math.random() * size());
int Pos2 = (int) (Math.random() * size());
boolean swap = array1[Pos1];
array2[Pos1] = array1[Pos2];
array2[Pos2] = swap;
Fitness = evaluate(array2);
double current = fits[value];
System.out.println(eval + " " +Fitness);
list = Arrays.asList(Fitness);
//I WANT TO SAVE ALL VALUES IN THIS LIST TO A FILE
//Keep track of best solution by only replacing it if a better fitness
//value is found by the algorithm
if(Fitness <= current)
{
for(int i=0; i<grid.size();i++) {
individuals[value][i] = array2[i];
fits[value] = Fitness;
}
}
else {
//value for the current solution
double difference = Fitness - current;
double random = Math.random();
double prob = Math.exp(-(double)Math.abs(difference)/Temp);
if(prob > random)
{
for(int i=0; i<grid.size();i++) {
individuals[value][i] = array1[i];
fits[value] = current;
}
}
}
//Cool the system
Temp *= 1-coolingRate;
eval++;
}
仅将一个条目写入文件的代码:
list = Arrays.asList(Fitness);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FNAME))) {
for (Double line : list) {
bw.write(line + "\n");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
【问题讨论】:
-
写入文件的代码是什么?
-
@AndrewS 这就是我寻求帮助的原因
-
有很多例子,你试过什么不起作用?
-
发布不起作用的代码。
-
simAnnealFit似乎是 double 类型,因此list = Arrays.asList(simAnnealFit);将是一个包含单个元素的列表。也许代码需要添加到list,然后在所有迭代之后写入文件。或者在每次迭代时写入文件,但不要覆盖文件。
标签: java eclipse arraylist fileoutputstream simulated-annealing