Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C++ linear interpolation

An example of linear interpolation in C++.

typedef std::vector DoubleVec;

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

  for (unsigned int i = 0; i < x.size(); i++) { 
    double newDist = ac_dfValue - x[i]; 
    if (newDist >= 0 && newDist < 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 < x.size(); i++){
    if (i < 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 < 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) - x axis and Y (std::vector

How to test it:

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

  DoubleVec xx;
  for (unsigned i = 1; i 

The result:

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



This post first appeared on HoriaCondrea, please read the originial post: here

Share the post

C++ linear interpolation

×

Subscribe to Horiacondrea

Get updates delivered right to your inbox!

Thank you for your subscription

×