1
\$\begingroup\$

I run a program of simulation N times (I use each time a different random numbers to initialize it). The results of the program are stored in 2N directories: every run produces two approximations. The directories contain the same files and have the following structure:

def-risultati-i, i = 1, ... , N

exc-risultati-i, i = 1, ... , N

Where def and exc are test names of the approximations. In each one of the directories there are histograms files (file-a.dat, file-b.dat, ...)

bin_left bin_right weight error

Where each bin is identified by the values of beginning and end.

I've written a program that takes a file from every directory and produces the average of the corresponding histogram. So for instance I take the file risultati.dat from

def-risultati-1, def-risultati-2, ... , def-risultati-N,

The code works fine but I'd like to improve the structure of the function that does all the job. There are some redundant passages (e.g. I store the values of the bins for the files taken from every directory, even though they are the same for every run of the program) and my c++ skills are rusty. I'm not sure about those nested for loops on a vector of vectors...

Here it is a "demo" of the program:

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <cmath>

void merge(int N, std::string appr, std::string title) {
  double a;
  std::string fin_dir = appr + "-totale";
  std::string init_dir = appr + "-risultati-";
  std::string num, dir;
  std::ifstream ri;
  std::ofstream out(fin_dir+title);
  std::vector<std::vector<double>> v_ri;

  for(int j=1; j<=N; j++){
    num = std::to_string(j);
    dir = init_dir+num+title;
    ri.open(dir);
    std::vector<double> v;

    while(ri >> a){
      v.push_back(a);
    }

    v_ri.push_back(v);
    ri.close();
  }

  a=0;
  std::vector<double> weight;
  for(int k=2; k<v_ri[0].size(); k=k+4){
    for(int j=0; j<v_ri.size(); j++){
      a = a+v_ri[j][k]/double(N);
    }
    weight.push_back(a);
    a=0;
  }

  a=0;
  std::vector<double> err;
  for(int k=3; k<v_ri[0].size(); k=k+4){
    for(int j=0; j<v_ri.size(); j++){
      a = a+pow(v_ri[j][k], 2)/double(N);
    }
    a = sqrt(a);
    err.push_back(a);
    a=0;
  }

  int cont = 0;
  for(int i=0; i<v_ri[0].size(); i=i+4){
    out << std::scientific << v_ri[0][i] << " " << v_ri[0][i+1] << " ";
    out << std::scientific << weight[cont] << " " << err[cont] << std::endl;
    cont++;
  }
}

int main(){
  //merge(numeber_of_directories, "exc"/"def", title)
  //title: /namefile.dat

  int N=3;

  merge(N, "exc", "/ris.dat");
  merge(N, "def", "/ris.dat");

  return 0;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.