// 生成高斯分布随机数直方图并进行拟合 void gaussFitTest() { // 设置随机数种子(可选,保证可重复性) gRandom->SetSeed(0); // 参数设置 int N = 100000; // 随机数数量 int nBins = 500; // 直方图分bin数 double mean = 50.0; // 高斯分布均值 double sigma = 10.0; // 高斯分布标准差 double xMin = mean - 5*sigma; // 范围下限 double xMax = mean + 5*sigma; // 范围上限 // 创建直方图 TH1D *hist = new TH1D("hist", "Gaussian Distribution", nBins, xMin, xMax); // 方法一:使用TRandom3生成随机数填充 TRandom3 *rand = new TRandom3(); for (int i = 0; i < N; i++) { double value = rand->Gaus(mean, sigma); hist->Fill(value); } // 方法二:使用预定义函数填充(更简洁) // hist->FillRandom("gaus", N); // "gaus" 是ROOT预定义的高斯函数 // 绘制直方图 TCanvas *c1 = new TCanvas("c1", "Gaussian Fit", 800, 600); hist->SetLineColor(kBlack); hist->SetFillColor(kCyan-9); hist->Draw("E"); // 定义拟合函数:f(x) = A * exp[-(x-μ)^2/(2σ^2)] // ROOT的高斯函数格式为 [0] * exp(-0.5*((x-[1])/[2])^2) TF1 *gaussFit = new TF1("gaussFit", "gaus", xMin, xMax); gaussFit->SetParameters(hist->GetMaximum(), mean, sigma); gaussFit->SetParNames("Amplitude", "Mean", "Sigma"); // 执行拟合 hist->Fit(gaussFit, "R"); // 显示拟合结果 gStyle->SetOptFit(1111); hist->Draw("E same"); // 输出拟合参数 cout << "拟合均值 = " << gaussFit->GetParameter(1) << " ± " << gaussFit->GetParError(1) << endl; cout << "拟合标准差 = " << gaussFit->GetParameter(2) << " ± " << gaussFit->GetParError(2) << endl; cout << "χ²/ndf = " << gaussFit->GetChisquare() / gaussFit->GetNDF() << endl; }