# Cleanest way to get error of a point in a TGraph, given an x value

I have a TGraph from which I want to extract the y-value and its error given some x-value.

For the y-value I can use graph->Eval(x), which works just fine even if x is between two points.

I cannot find a similar function to Eval for interpolating the error between points. As a workaround, I wanted to find the closest point to x, such that I could use getErrorY(closestPoint). However, I cannot find a function that will tell me the point index given x.

I could write a loop over points, calculate the distance to my x-value, etc. But is there a cleaner, quicker way?

Welcome to the ROOT forum

Yes that would be the way to do it.
For instance:

``````Double_t GetClosestXIndex(const TGraph* graph, Double_t xValue) {
Double_t minDist = DBL_MAX;
Int_t closestIndex = -1;

// Iterate over all points in the graph
for (Int_t i = 0; i < graph->GetN(); ++i) {
Double_t x, y;
graph->GetPoint(i, x, y);

// Calculate the distance between the current x-value and the desired x-value
Double_t dist = TMath::Abs(x - xValue);

// Update the closest index if a closer point is found
if (dist < minDist) {
minDist = dist;
closestIndex = i;
}
}

return closestIndex;
}
``````

then:

``````TGraph* graph = ...;  // Your TGraph object

Double_t xValue = 3.14159;  // Your desired x-value

Int_t closestIndex = GetClosestXIndex(graph, xValue);
Double_t closestYError = graph->GetErrorY(closestIndex);

// Print the result
std::cout << "Closest point index: " << closestIndex << std::endl;
std::cout << "Closest point y-error: " << closestYError << std::endl;
``````

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.