You are here

Function Interpolation

Interpolation is done with the class ROOT::Math::Interpolation. This class is instantiated with an interpolation method, passed as an enumeration in the constructor. These methods are implemented using GSL . The class provides additional methods for computing derivatives and integrals of interpolating functions.

#include "Math/Polynomial.h"
#include "Math/Interpolator.h"
 
#include <iostream>
#include "TCanvas.h"
#include "TGraph.h"
 
 
void interpolation()
{
   using namespace std;
 
   Float_t xmin = -3, xmax = 2.5;
 
   const Int_t nb = 100;
   Double_t x[nb], y[nb], iy[nb];
 
   const Int_t ni = 10;
   Double_t xi[ni], yi[ni];
 
   ROOT::Math::Polynomial polyf(4);
 
   double p[4];
   p[0] = 1;
   p[1] = -1.5;
   p[2] = 1;
   p[3] = 1;
   polyf.SetParameters(p);
   ROOT::Math::IBaseFunctionOneDim & f1 = polyf;
 
   // You can choose among the following methods:
   // CSPLINE, LINEAR, POLYNOMIAL,
   // CSPLINE_PERIODIC, AKIMA, AKIMA_PERIODIC
   ROOT::Math::Interpolator inter(ni, ROOT::Math::Interpolation::kPOLYNOMIAL);
   for ( Int_t i = 0; i < ni; ++i )
   {   
      xi[i] = (Double_t) i*(xmax-xmin)/(ni-1) + xmin;
      yi[i] = f1(xi[i]);
   }
   inter.SetData(ni, xi, yi);
 
   for ( Int_t i = 0; i < nb; ++i )
   {
      x[i]  = (Double_t) i*(xmax-xmin)/(nb-1) + xmin;
      y[i]  = f1(x[i]);
      iy[i] = inter.Eval(x[i]);
   }
 
    new TCanvas("c1", "Two Graphs", 600, 400); 
 
   TGraph* gf = new TGraph(ni, xi, yi);
   gf->SetLineColor(14);
   gf->SetLineWidth(3);
   gf->SetTitle("Function: sin(x)");
   gf->SetMarkerStyle(22);
   gf->Draw("AP");
 
   TGraph* gi = new TGraph(nb, x, iy);
   gi->SetLineColor(28);
   gi->SetLineWidth(1);
   gi->SetTitle("Integral");
   gi->Draw("SAME L"); 
 
   cout << "done!" << endl;
 
   // Don't forget to delete all the objects once it's finished!
}