类加计算在作图中是十分常用的一种计算方法,例如,将离散数据的微分坐标改成积分坐标就要用到叠加的方式。ROOT官方教程的cumulative.C就是演示这一方法。
下面给出具体代码步骤:
创建一维直方图:
TH1* h = new TH1D("h", "h", 100, -5., 5.);
生成随机数种子:
gRandom->SetSeed();
生成随机数填充直方图:
h->FillRandom("gaus", 1u << 16); //1u << 16是位掩码,指的是2^16
创建新的直方图hc,类加h:
TH1* hc = h->GetCumulative();
检查hc是否正确:
Double_t* integral = h->GetIntegral(); //获得h的积分值
for (Int_t i = 1; i <= hc->GetNbinsX(); ++i) {
assert(std::abs(integral[i] * h->GetEntries() - hc->GetBinContent(i)) < 1e-7);
}
绘制直方图及其累积分布:
TCanvas* c = new TCanvas;
c->Divide(1,2);
c->cd(1);
h->Draw();
c->cd(2);
hc->Draw();
c->Update();
代码地址:https://github.com/root-project/root/blob/master/tutorials/hist/cumulative.C