Hello,
Can anybody here help me with generating random numbers and then saving them in a .dat file ?
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctime>
int main(int argc, char* argv[])
{
std::srand(std::time(nullptr));
std::ofstream myfile;
myfile.open("rnd_numbers.dat");
for (int i=0; i<100; ++i)
myfile << std::rand() << std::endl;
myfile.close();
system("pause");
return 0;
}
Read http://www.cplusplus.com/reference/random/
and/or watch: https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
In ROOT, you can also use TRandom3 (Mersenne Twister).
#include "TRandom.h"
#include <fstream>
void random(void) {
std::ofstream ofs("random.dat", std::ofstream::out);
gRandom->SetSeed(0); // make it really random
for (int i = 0; i < 1000; i++) ofs << gRandom->Rndm() << std::endl;
ofs.close();
}
It worked . Thank you.
Can you tell me how i can make a histogram with this .dat file ?
#include "TTree.h"
#include "TH1.h"
void draw(void) {
TTree *t = new TTree("t", "temoporary tree with velocities");
t->ReadFile("random.dat", "v/D");
TH1D *h = new TH1D("h", "histogram;random;n", 100, 0.0, 1.0);
t->Project("h", "v");
delete t; // no longer needed
h->Draw("L");
}
It did worked but it is showing a blank plot with just x and y axis . Am i doing something wrong ?
Hi,
is there a reason why you want to work with ascii files rather than optimised ROOT files?
D
Hhhh Dpiparo, Actually I am going to work with AMPT model . So, I am learning how to deal with .dat files before starting my work. That’s my job. hh
Thanks for asking .
Hi,
thanks, I see. I attach* a complete example which allows you to write and read data in dat format and analyse it “the modern way”, with TDataFrame.
The advantages of this setup, in my opinion, are:
- if needed, to analyse your data in parallel
- dump your datasets in ROOT format
- preserve your entire analysis in case you switch to another file format (e.g. ROOT)
- more concise way of expressing the analysis with a declarative approach
Cheers,
D
using namespace ROOT::Experimental;
// Configuration
auto nNumbers = 1024;
auto seed = 1;
auto filename = "random.dat";
void write()
{
std::ofstream ofs(filename, std::ofstream::out);
TRandom3 myGen(seed);
auto printNumber = [&]() {
ofs << myGen.Rndm() << std::endl;
};
TDataFrame f(nNumbers);
f.Foreach(printNumber);
ofs.close();
}
void read()
{
auto f = TDF::MakeCsvDataFrame(filename, false); // we have no header
auto h = f.Histo1D("Col0"); // the dat file has no header, the name of the column is Col0
TCanvas c;
h->Draw();
c.Print("myHisto.png");
}
void readWrite()
{
write();
read();
}
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.