Skip to content

Commit 8f0a7cc

Browse files
committed
[hist] Apply suggestions by Jonas R.
Implement suggestions by Jonas R. to make FindFixBin more robust to numerical errors
1 parent 07396f9 commit 8f0a7cc

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

hist/hist/src/TAxis.cxx

+14-14
Original file line numberDiff line numberDiff line change
@@ -402,22 +402,22 @@ Int_t TAxis::FindFixBin(const char *label) const
402402
////////////////////////////////////////////////////////////////////////////////
403403
Int_t TAxis::DoFindFixBin(Double_t x) const
404404
{
405-
int bin = 0;
406405
if (!fXbins.fN) { //*-* fix bins
407-
bin = 1 + int (fNbins * (x-fXmin)/(fXmax-fXmin) );
408-
// apply correction when x is at the bin edge value
409-
// (computed as in GetBinLowEdge) a numerical error in the
410-
// above division can cause a migration in a neighbour bin.
411-
double binwidth = (fXmax - fXmin) / Double_t(fNbins);
412-
double upEdge = fXmin + (bin) * binwidth;
413-
double lowEdge = fXmin + (bin - 1) * binwidth;
414-
if (upEdge <= x) bin += 1;
415-
if (lowEdge > x) bin -= 1;
416-
} else { //*-* variable bin sizes
417-
//for (bin =1; x >= fXbins.fArray[bin]; bin++);
418-
bin = 1 + TMath::BinarySearch(fXbins.fN,fXbins.fArray,x);
406+
// shift x and fXmax by fXmin:
407+
x = x - fXmin;
408+
const double b = fXmax - fXmin;
409+
const double s = fNbins * x; // scaled version of x
410+
double m = std::floor(s / b);
411+
// iterative correction in case of floating point errors due to floating point division
412+
while (m * b > s) // if left bin boundary is greater then x, decrement
413+
m = m - 1;
414+
while ((m + 1) * b <= s) //if right bin boundary is smaller or equal, increment
415+
m = m + 1;
416+
return 1 + Int_t(m);
417+
} else { //*-* variable bin sizes
418+
// for (bin =1; x >= fXbins.fArray[bin]; bin++);
419+
return 1 + TMath::BinarySearch(fXbins.fN, fXbins.fArray, x);
419420
}
420-
return bin;
421421
}
422422

423423
////////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)