lundi 27 juillet 2020

Why is this sum of floats rounding?

I've written a simple C++ macro for use with the CERN ROOT data analysis framework. It takes in a data file (essentially a spreadsheet) with day, hour, minute, second, and sub-second columns. My goal here is to convert that data into a file of timestamps, in seconds. Everything works fine up to adding the sub seconds. For some reason, it seems to be rounding the result. For example, one timestamp is:

804267 + 0.5606663227081298828125 = 804267.5625

Another is:

155034 + 0.0958281949540391919293 = 155034

ROOT::RDataFrame d("N", "mydata1.root");
TFile *rfout = new TFile("./mydata2.root", "recreate");
TNtuple *N = new TNtuple("N","N","TIMESTAMP");

vector<float> timestamp;
int i;

d.Foreach([&](float day){timestamp.push_back(day*86400.00);},{"day"});
d.Foreach([&](float hr){timestamp.at(i) = timestamp.at(i)+(hr*3600);i++;},{"hr"});
i=0;
d.Foreach([&](float min){timestamp.at(i) = timestamp.at(i)+(min*60);i++;},{"min"});
i=0;
d.Foreach([&](float sec){timestamp.at(i) = timestamp.at(i)+sec;i++;},{"sec"});

i=0;
float j;
d.Foreach([&](float sub){
    while(sub > 1){
        sub = sub/10;
    }
    j = sub + timestamp.at(i);
    N->Fill(j);
    std::cout << std::setprecision(100) << j << " " << sub <<std::endl;
    i++;
},{"subsecond"});

rfout->Write();
rfout->Close();
abort();

}`

Aucun commentaire:

Enregistrer un commentaire