Home | News | Documentation | Download

Calculate local minima and maxima of a periodic function

I have a periodic function for x(t) very similar to a cos function. I want to calculate the time at which local maxima and minima occur. I know how to do this with if loops checking each time that x(t1)>x(t0), etc, but I wonder if there is a ROOT function to help me with this, or a better approach.

In what kind of object is stored your function ? TGraph ? TF1 ?

Sorry for the delay in my response. The object is stored in a TTree, and I make a TGraph with the Draw option

So you have a TGragh. You can easily loop on the TGraph points and use GetPoint to retrieve the X and Y values of each points

Right, I was just wondering if there was a function that could give me the maxima or minima in some defined range

Not for TGraph. GetMaximum() and GetMinimum() work on the whole range. But the method is really easy to write. Something like:

double GetMaximumRange(TGraph *g, double x1, double x2) {
   double n = g->GetN();
   double max = 0;
   double x,y;
   for (int i=0; i<n; i++) {
      g->GetPoint(i,x,y);
      if (x>x1 && x <x2) {
         if (y>max) max=y
      }
   }
   return max;
}