# How does GetChisquare() is calculated when you fit data?!

chi_square_ndf = ex.GetChisquare() / ex.GetNDF(); I want to calculate the goodness of my fit, but I cannot find what is the equation behind chi2. Is it like this?:
# Calculate chi-square
residuals = unique_charges - fitted_charges
chi_square = np.sum((residuals ** 2) / fitted_charges)
ndof = len(unique_charges) - len(popt)
chi2_ndf = chi_square / ndof if ndof != 0 else float(‘inf’)
thanks you!

Hi Elena,

Could you please give us some context? What is ex?

Best,
D

Hi Elena,

\chi^2 is defined as follow:

\chi^2 = \sum_{i}{ \left(\frac{y(i) - f(x(i) | p )}{e(i)} \right)^2 }.

is the sum of the residual squared weighted with the inverse of the error squared.

Here is a code I worked in which calculates \chi^2 manually and compares with what root shows. Hope it helps.

    TRandom3 *rand = new TRandom3();

TH1F *hist = new TH1F("hist", " ; x; y", 100, 0, 100);

for (int i = 0; i < 10000; ++i) {
hist->Fill(rand->Gaus(50, 10));
}

hist->Draw("E1");

TF1 *fit = new TF1("fit", "gaus");
hist->Fit(fit);

cout << "Chi-square from fit: " << fit->GetChisquare() << endl;

double chi = 0.0;

for (int i = 1; i < 100; ++i)
{
double binCenter = hist->GetBinCenter(i);
double binContent = hist->GetBinContent(i);
double binError = hist->GetBinError(i);
double fitValue = fit->Eval(binCenter);

if (binError != 0)
{
chi += (binContent - fitValue) * (binContent - fitValue) / (binError * binError);
}
}

cout << "Manually Calculated Chi-square: " << chi << endl;



Hello! thank you for the answer! ex is:

        std::stringstream function_def;
function_def << max_charge << "*pow((1-exp(-[0]*x)),[1])";

auto to_string = function_def.str();
TF1 ex("tf_name", to_string.c_str());

ex.SetParameters(1./12., 1);

std::stringstream predicate;

data->Fit("tf_name", "charge:qtp", predicate.str().c_str(), "WQ0N");

double chi_square_ndf = ex.GetChisquare() / ex.GetNDF();
calibrationParams[p] = { ex.GetParameter(0), ex.GetParameter(1), max_charge + 0.001f, chi_square_ndf };


I fit adc values vs charge. how does the chi2 is calculated?
each adc value is the average of events adc = ((Float_t)v.total) / v.samples;. do I need to calculate also the Standard error of the mean (SEM)? does root compensated for that while it does the fit? how do I add it, or I add error bars? an example or a plot below. Thank you very much in advance