C++ linear interpolation

An example of linear interpolation in C++.

typedef std::vector<double> DoubleVec;

int findNearestNeighbourIndex(const double ac_dfValue, 
                              DoubleVec x)
{
  double lv_dfDistance = DBL_MAX;
  int lv_nIndex = -1;

  for (unsigned int i = 0; i &lt; x.size(); i++) { 
    double newDist = ac_dfValue - x[i]; 
    if (newDist &gt;= 0 &amp;&amp; newDist &lt; lv_dfDistance) {
        lv_dfDistance = newDist;
        lv_nIndex = i;
    }
  }

  return lv_nIndex;
}

DoubleVec interpolation(DoubleVec x, DoubleVec y, 
                 DoubleVec xx)
{
  double dx, dy;
  DoubleVec slope, intercept, result;
  slope.resize(x.size());
  intercept.resize(x.size());
  result.resize(xx.size());
  int indiceEnVector;

  for (unsigned i = 0; i &lt; x.size(); i++){
    if (i &lt; x.size() - 1){
      dx = x[i + 1] - x[i];
      dy = y[i + 1] - y[i];
      slope[i] = dy / dx;
      intercept[i] = y[i] - x[i] * slope[i];
    }
    else{
      slope[i] = slope[i - 1];
      intercept[i] = intercept[i - 1];
    }
  }

  for (unsigned i = 0; i &lt; xx.size(); i++) {
    indiceEnVector = findNearestNeighbourIndex(xx[i], x);
    if (indiceEnVector != -1){
      result[i] = slope[indiceEnVector] * 
                  xx[i] + intercept[indiceEnVector];
      }
    else
      result[i] = DBL_MAX;
  }
  return result;
}

Returns the interpolated values for the XX grid(std::vector), using as reference the X (std::vector<double, argument variable>) – x axis and Y (std::vector<double, argument variable) – y axis.

How to test it:

int main()
{
  DoubleVec x =  {1, 5, 10};
  DoubleVec y = {10, 50, 100};

  DoubleVec xx;
  for (unsigned i = 1; i < 10; ++i)
    xx.push_back(i);

  DoubleVec res = interpolation(x,y,xx);

  return 0;
}

The result:

10 ; 20 ; 30 ; 40 ; 50 ; 60 ; 70 ; 80 ; 90 ;

Leave a Reply

Your email address will not be published. Required fields are marked *


*

WordPress SEO