【问题标题】:Write list of doubles to file将双打列表写入文件
【发布时间】: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


【解决方案1】:

用于将双精度数组写入文件的实现:

ArrayList<Double> yourArray = new ArrayList<>();
final String FILENAME = "sample.txt";
            list.add(arrayValue)
            try ( BufferedWriter bw = new BufferedWriter (new FileWriter (FILENAME)) ) 
            {           
                for (Double line : yourArray) {
                    bw.write (line + "\n");
                    bw.newLine();
                }

                bw.close ();

            } catch (IOException e) {
                e.printStackTrace ();
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多